Direct mail API for Google Cloud
Direct mail API for Google Cloud apps: a Cloud Run job reads who to mail from your database and sends them to Mailr 1,000 per request, Secret Manager hands it the key as an environment variable, and Cloud Scheduler starts it every night. Single postcards go through a Cloud Run service that Cloud Tasks retries.
What to mail from Google Cloud
| When this happens | Mail this |
|---|---|
| Cloud Scheduler starts the nightly Cloud Run job | Win-back postcards to customers 60+ days past their last order, 1,000 per request. (Win-back) |
| Your app queues a Cloud Tasks task when an order ships | A thank-you card, retried with backoff if Mailr can't be reached. (First-order thank you) |
| A Pub/Sub push subscription delivers an event to your Cloud Run service | A card per event, with the record id from the message as the Idempotency-Key, because Pub/Sub retries until your service returns a success code. |
Set it up
- Put the key in Secret Manager. Create the secret with your mlr_test_ key as version 1, and grant one service account Secret Manager Secret Accessor (roles/secretmanager.secretAccessor) on it. The job and the service both run as that account.
- Deploy the job. gcloud run jobs deploy builds ./job from source, and --set-secrets maps the secret to MAILR_API_KEY. Pin a version number rather than latest, as Google recommends; secrets in environment variables are read when an instance starts.
- Schedule it. Cloud Scheduler calls the Cloud Run Admin API's jobs:run method with an OAuth token from the service account, which needs Cloud Run Invoker (roles/run.invoker) on the job. Run it once by hand with gcloud run jobs execute mailr-nightly and check the pieces in your Mailr dashboard.
- Queue single postcards. Deploy the sender as a private Cloud Run service and create a Cloud Tasks queue with --max-attempts, --min-backoff and --max-backoff. Your app creates one task per order, named after the order, and the task calls the service with an OIDC token.
- Go live. Add your mlr_live_ key as version 2 of the secret and point the job and the service at it with --update-secrets, as in the last lines of deploy.sh.
Deploy and code
PROJECT=$(gcloud config get-value project)
REGION=us-central1
SA=mailr-runner@$PROJECT.iam.gserviceaccount.com
# 1. The Mailr key in Secret Manager (version 1 is your test key), readable by one service account
gcloud iam service-accounts create mailr-runner
printf "%s" "$MAILR_TEST_KEY" | gcloud secrets create mailr-api-key --data-file=-
gcloud secrets add-iam-policy-binding mailr-api-key \
--member="serviceAccount:$SA" --role="roles/secretmanager.secretAccessor"
# 2. The nightly batch as a Cloud Run job, built from ./job (package.json "start": "node index.mjs")
gcloud run jobs deploy mailr-nightly --source ./job --region $REGION \
--service-account $SA \
--set-secrets MAILR_API_KEY=mailr-api-key:1 \
--task-timeout 30m --max-retries 3
# 3. Cloud Scheduler runs it at 2:00 every night
gcloud run jobs add-iam-policy-binding mailr-nightly --region $REGION \
--member="serviceAccount:$SA" --role="roles/run.invoker"
gcloud scheduler jobs create http mailr-nightly-2am --location $REGION \
--schedule "0 2 * * *" --time-zone "America/Phoenix" \
--uri "https://run.googleapis.com/v2/projects/$PROJECT/locations/$REGION/jobs/mailr-nightly:run" \
--http-method POST \
--oauth-service-account-email $SA
# 4. Single postcards: a private Cloud Run service, and a Cloud Tasks queue that retries it
gcloud run deploy mailr-sender --source ./service --region $REGION \
--service-account $SA --no-allow-unauthenticated \
--set-secrets MAILR_API_KEY=mailr-api-key:1
gcloud run services add-iam-policy-binding mailr-sender --region $REGION \
--member="serviceAccount:$SA" --role="roles/run.invoker"
gcloud tasks queues create mailr --location $REGION \
--max-attempts 10 --min-backoff 10s --max-backoff 600s
# Going live: add version 2 with your mlr_live_ key, then point the job and service at it
# printf "%s" "$MAILR_LIVE_KEY" | gcloud secrets versions add mailr-api-key --data-file=-
# gcloud run jobs update mailr-nightly --region $REGION --update-secrets MAILR_API_KEY=mailr-api-key:2
# gcloud run services update mailr-sender --region $REGION --update-secrets MAILR_API_KEY=mailr-api-key:2- A Cloud Run job task times out after 10 minutes by default (up to 168 hours) and is retried up to 3 times by default (0 to 10). A retry runs the whole task again: batches already made come back from the same Idempotency-Key within 24 hours, and saved piece ids keep later runs from picking those customers.
- Cloud Scheduler may retry a request, which can start the job twice. The same keys make the second run a replay.
- Cloud Tasks handlers time out after 10 minutes by default (30 at most), and any response other than 2xx is retried on the queue's schedule. The handler returns 503 only for a 409 or 5xx from Mailr; a 422 is logged and not retried, since it won't pass on a later try.
- Naming a task lets Cloud Tasks drop a duplicate: creating the same name again fails with ALREADY_EXISTS (code 6), which the code ignores.
- Pub/Sub push treats 200 and 204 as acknowledged and retries error codes. A dead-letter topic takes a message after 5 to 100 delivery attempts.
What it costs
Each live piece is paid from your Mailr balance, printing and postage included: a 4x6 postcard is $0.85, a 6x9 $0.89 and an 8.5x11 letter $0.95 on pay as you go, less on a plan. Test pieces are free. All prices.
Templates that fit: Win-back (6x11), First-order thank you (6x9).
Questions
Cloud Run functions or Cloud Run?
Either. Cloud Run functions (formerly Cloud Functions) run on Cloud Run, so an HTTP function can do what service/index.mjs does. The nightly batch fits a job better: it runs to completion without holding an HTTP request open.
Will a retry print a batch twice?
Not within 24 hours. The key is a hash of the customer ids in the batch, so the same customers get the first batch back. Order the query by id so a rerun builds the same groups of 1,000.
How do I see delivery status?
Point a Mailr webhook at a Cloud Run service that checks Mailr-Signature and records postcard.printed and postcard.mailed; USPS delivery scans aren't reported for live pieces yet. Or retrieve a piece with GET /v1/postcards/{id}, or list a batch's pieces with GET /v1/postcards?batch={id}, which pages with starting_after.
Where does the key live?
Only in Secret Manager. Cloud Run reads the pinned version into MAILR_API_KEY when an instance starts, and only the mailr-runner service account can read the secret.
What does it cost?
Each live piece is one price with printing and postage included: a 6x9 postcard is $0.89 on pay as you go and less on a plan. Test pieces are free and never print.