Nov 23, 20267 min read

Build a Daily Email Digest Backend

Sending one summary email per user at 8:00 in their own time zone, skipping empty digests, never sending twice on the same day and honouring one-click unsubscribe, with a Go example on Encore using cron, Pub/Sub and Postgres.

Illustration for Build a Daily Email Digest Backend

A daily digest replaces a stream of individual emails with one summary, such as "5 new comments on your posts". It is quieter, and it often brings back users who turned off every real-time notification.

It also raises questions single emails never did: whose 8:00 it is, what happens when the job runs twice and what to send when nothing happened. This guide answers them and builds the backend in Go.

How do you send at 8:00 in every user's time zone?

Store each user's IANA time zone name, such as Europe/Vienna or America/New_York, not a fixed UTC offset, since offsets change with daylight saving time. Run one job every hour that selects users whose current local hour is the send hour:

SELECT user_id, (now() AT TIME ZONE timezone)::date AS local_date FROM digest_subscribers WHERE enabled AND extract(hour FROM now() AT TIME ZONE timezone) = 8;

Each hourly run picks up the slice of users for whom it is 8:00 right now, which also spreads sending across the day instead of firing every email at once. A handful of time zones sit on half-hour or 45-minute offsets, and those users get their digest at 8:30 or 8:45 local time with this query, which is usually fine.

How do you avoid double sends?

A digest is identified by the user and their local date. Insert a row for that pair before sending and mark it sent afterwards, with a primary key on (user_id, local_date). A redelivered job or an overlapping run finds the row, sees sent and stops. If the process dies between sending and marking, the retry sends again, which is the rare at-least-once case, and the alternative of marking first would drop the digest silently instead.

What should a digest contain?

The events since the user's last sent digest, falling back to the last 24 hours for the first one, grouped by kind and capped at a sensible length with a link to see everything. When there are no events, mark the digest skipped and send nothing. An empty "nothing new today" email trains people to ignore the sender and costs reputation with mailbox providers for no benefit.

What are the unsubscribe requirements?

Digests count as subscribed bulk mail. RFC 8058 defines one-click unsubscribe through two headers, List-Unsubscribe with an HTTPS URL and List-Unsubscribe-Post: List-Unsubscribe=One-Click, and a mail client that supports it sends a POST to that URL when the user clicks unsubscribe. Google's sender guidelines require this for bulk senders, so the URL must carry a per-user token and work without a login.

Daily digests with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the schedule, the per-user queue and the digest tables are declared in one Go service. An Encore cron job calls the selection endpoint every hour, a Pub/Sub topic carries one job per user so sends retry independently, and an Encore Postgres database holds subscribers, events and sent digests. The cron job is managed by the Encore platform, and the topic and database are provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- digest/migrations/1_create_digest.up.sql CREATE TABLE digest_subscribers ( user_id TEXT PRIMARY KEY, email TEXT NOT NULL, timezone TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT true, unsub_token TEXT NOT NULL UNIQUE ); CREATE TABLE events ( id BIGSERIAL PRIMARY KEY, user_id TEXT NOT NULL, summary TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX events_user_time ON events (user_id, created_at); CREATE TABLE digests ( user_id TEXT NOT NULL, local_date DATE NOT NULL, status TEXT NOT NULL CHECK (status IN ('sending', 'sent', 'skipped')), event_count INT NOT NULL DEFAULT 0, sent_at TIMESTAMPTZ, PRIMARY KEY (user_id, local_date) );
// digest/digest.go package digest import ( "bytes" "context" "encoding/json" "fmt" "html" "net/http" "strings" "time" "encore.dev" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("digest", sqldb.DatabaseConfig{Migrations: "./migrations"}) var secrets struct { ResendAPIKey string } type DigestJob struct { UserID string LocalDate string // YYYY-MM-DD in the user's time zone } var Jobs = pubsub.NewTopic[*DigestJob]("digest-jobs", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) var _ = cron.NewJob("queue-digests", cron.JobConfig{ Title: "Queue daily digests for users at 08:00 local time", Every: 1 * cron.Hour, Endpoint: QueueDigests, }) type QueueResult struct { Queued int } //encore:api private func QueueDigests(ctx context.Context) (*QueueResult, error) { rows, err := db.Query(ctx, ` SELECT user_id, to_char((now() AT TIME ZONE timezone)::date, 'YYYY-MM-DD') FROM digest_subscribers WHERE enabled AND extract(hour FROM now() AT TIME ZONE timezone) = 8`) if err != nil { return nil, err } defer rows.Close() res := &QueueResult{} for rows.Next() { job := &DigestJob{} if err := rows.Scan(&job.UserID, &job.LocalDate); err != nil { return nil, err } if _, err := Jobs.Publish(ctx, job); err != nil { return nil, err } res.Queued++ } return res, rows.Err() } var _ = pubsub.NewSubscription(Jobs, "send-digest", pubsub.SubscriptionConfig[*DigestJob]{ Handler: sendDigest, MaxConcurrency: 10, }) func sendDigest(ctx context.Context, job *DigestJob) error { if _, err := db.Exec(ctx, `INSERT INTO digests (user_id, local_date, status) VALUES ($1, $2::date, 'sending') ON CONFLICT DO NOTHING`, job.UserID, job.LocalDate); err != nil { return err } var status string if err := db.QueryRow(ctx, `SELECT status FROM digests WHERE user_id = $1 AND local_date = $2::date`, job.UserID, job.LocalDate).Scan(&status); err != nil { return err } if status != "sending" { return nil // already sent or skipped } var email, token string var enabled bool if err := db.QueryRow(ctx, `SELECT email, unsub_token, enabled FROM digest_subscribers WHERE user_id = $1`, job.UserID).Scan(&email, &token, &enabled); err != nil { return err } // The cutoff is fixed before the query and saved as the checkpoint, so an // event committed during the run is picked up by the next digest. cutoff := time.Now() rows, err := db.Query(ctx, ` SELECT summary FROM events WHERE user_id = $1 AND created_at <= $2 AND created_at > coalesce( (SELECT max(sent_at) FROM digests WHERE user_id = $1 AND status IN ('sent', 'skipped')), now() - interval '24 hours') ORDER BY created_at LIMIT 20`, job.UserID, cutoff) if err != nil { return err } var items []string for rows.Next() { var s string if err := rows.Scan(&s); err != nil { rows.Close() return err } items = append(items, "<li>"+html.EscapeString(s)+"</li>") } rows.Close() if err := rows.Err(); err != nil { return err } if !enabled || len(items) == 0 { // sent_at doubles as the checkpoint, so a skipped day still moves it forward. _, err := db.Exec(ctx, `UPDATE digests SET status = 'skipped', sent_at = $3 WHERE user_id = $1 AND local_date = $2::date AND status = 'sending'`, job.UserID, job.LocalDate, cutoff) return err } unsubURL := encore.Meta().APIBaseURL.String() + "/digest/unsubscribe/" + token // The idempotency key makes a second worker on the same user and day a no-op at the provider. if err := send(ctx, email, fmt.Sprintf("Your daily summary: %d updates", len(items)), "<ul>"+strings.Join(items, "")+"</ul>", unsubURL, "digest-"+job.UserID+"-"+job.LocalDate); err != nil { return err } // The status check means an overlapping worker cannot overwrite a finished row. _, err = db.Exec(ctx, `UPDATE digests SET status = 'sent', event_count = $3, sent_at = $4 WHERE user_id = $1 AND local_date = $2::date AND status = 'sending'`, job.UserID, job.LocalDate, len(items), cutoff) return err } func send(ctx context.Context, to, subject, htmlBody, unsubURL, idempotencyKey string) error { body, _ := json.Marshal(map[string]any{ "from": "Example <digest@example.com>", "to": to, "subject": subject, "html": htmlBody, "headers": map[string]string{ "List-Unsubscribe": "<" + unsubURL + ">", "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", }, }) req, err := http.NewRequestWithContext(ctx, "POST", "https://api.resend.com/emails", bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+secrets.ResendAPIKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("Idempotency-Key", idempotencyKey) client := &http.Client{Timeout: 15 * time.Second} resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("email provider returned %d", resp.StatusCode) } return nil } // Unsubscribe handles the RFC 8058 one-click POST, which carries a form body, so it is a raw endpoint. // //encore:api public raw method=POST path=/digest/unsubscribe/:token func Unsubscribe(w http.ResponseWriter, req *http.Request) { token := encore.CurrentRequest().PathParams.Get("token") if _, err := db.Exec(req.Context(), `UPDATE digest_subscribers SET enabled = false WHERE unsub_token = $1`, token); err != nil { http.Error(w, "try again later", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }

The cron job does not run under encore run or in preview environments, so locally you call QueueDigests from the development dashboard after seeding a subscriber whose time zone puts them at 8:00, and follow the publish, the digest query and the send in one trace. In deployed environments it runs at the top of every hour. Summaries are HTML-escaped before they go into the email, since event text often comes from other users.

Every rule in this flow, from the send hour and the 20-item cap to the skip on empty days, lives in this file next to the schedule, so an agent asked to add a weekly digest can add a second job and a cadence column and test both locally in one change.

Best fit: Products that want to replace noisy per-event email with one summary a day, sent from their own cloud account and their own Postgres data.

Frequently asked questions

How do you send a daily digest at each user's local time?

Store each user's IANA time zone and run a job every hour that selects users whose current local hour is the send hour, for example with extract(hour FROM now() AT TIME ZONE timezone) = 8 in Postgres. Each run then only queues the users for whom it is 8:00 right now.

How do you avoid sending the same digest twice?

Record each digest in a table keyed on user and local date with a status column. A retried job sees the existing row and returns if the status is already sent, so queue redeliveries and overlapping job runs cannot produce a second email for the same day.

Do digest emails need a one-click unsubscribe?

Yes, for anyone sending in volume to Gmail or Yahoo users. Both require bulk senders to support one-click unsubscribe as defined in RFC 8058, with List-Unsubscribe and List-Unsubscribe-Post headers and a POST endpoint that unsubscribes without a login.

How do I build an email digest with Encore?

Add an hourly Encore cron job that calls an endpoint selecting the users due for a digest and publishing one Pub/Sub message per user. A subscriber builds the digest from an Encore Postgres database, records it and sends it. Cron jobs run in deployed environments, so call the endpoint by hand when testing locally.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders