Nov 17, 202615 min read

Abandoned Cart Recovery Backend: Cart Events, Reminder Sweeps and Discount Codes

Design the backend behind abandoned cart emails: cart events that arrive out of order, a scheduled sweep that queues each reminder once, sends that re-check the cart, one-click unsubscribe and single-use discount codes, then build it in Go with Encore.

Illustration for Abandoned Cart Recovery Backend: Cart Events, Reminder Sweeps and Discount Codes

An abandoned cart email looks like a cron job and a template, and most first versions are exactly that, a query every few minutes for carts older than an hour and a loop that sends mail. The bugs show up in production: a customer who checked out five minutes ago gets "you left something behind", a retry sends the 10% code twice, and an unsubscribe on Monday does nothing for a reminder already queued on Sunday.

This guide designs a recovery backend that avoids those: cart events consumed from Pub/Sub with late update and checkout events ignored, a sweep that queues each reminder exactly once, sends that re-check the cart at the last moment, one-click unsubscribe and discount codes that work once. It starts with the data model and a hand-built version on AWS, then builds it in Go with Encore.

The recovery backend at a glance

JobPatternHand-built on AWSWith Encore in your AWS account
Cart stateUpsert from cart events, ignore older eventsSNS, SQS and a worker on RDSPub/Sub subscription on an Encore database
Find abandoned cartsSweep every 15 minutes on idle_sinceEventBridge Scheduler or an ECS scheduled taskCron job, Encore platform managed
Queue onceInsert (cart, idle_since, step), conflict means already queuedSame databaseSame database
SendRe-check the cart, provider idempotency key, mark sentSQS workerPub/Sub subscription
UnsubscribeSigned link, one-click POST, hashed addressAPI endpointRaw endpoint
Discount codeOne per cart, expires, redeemed once per orderSame databaseSame database

Cart events and idle time

The storefront publishes an event on every cart change and on checkout, with the cart ID, the email if known, marketing consent, the total and the time it happened. The recovery service keeps its own small table of carts from those events instead of querying the storefront database, which keeps a slow sweep away from checkout traffic.

SNS with standard SQS queues, which is what most AWS setups use, can deliver a message more than once and out of order, so the upsert only applies an event newer than last_event_at and never touches a checked-out cart. Without that guard, a late "updated" event can arrive after "checked_out" and put a paid order back into the reminder sequence.

idle_since is the time of the latest change: every change moves it forward, which starts a new idle period, and reminders are keyed by that period, so a reminder queued for an older period is skipped at send time rather than mailed for a cart the customer has since edited.

One sweep, each reminder queued once

A timer per cart is tempting and hard to cancel. A sweep every 15 minutes is simpler: insert a row into reminders for every cart that has crossed a step, with ON CONFLICT DO NOTHING on the primary key (cart_id, idle_since, step). Overlapping runs, retries and a manual run from a dashboard all hit that key, and the insert itself is the claim. Step 1 goes out after an hour and step 2, with a code, after a day, and each step has an upper bound, so a cart first seen at 30 hours idle gets only the second email.

The sweep then marks rows with published_at and puts them on a topic. A publish that fails leaves the row with an old published_at, and the next run after ten minutes publishes it again, which the sender treats as a duplicate if it was in fact delivered.

Sends that re-check the cart

The sender loads the reminder and the cart in one query and only continues if the reminder is still queued, the cart has not checked out, idle_since has not moved and the address is not unsubscribed, and anything else marks the row skipped. That check runs seconds before the email leaves, which is what catches the checkout that happened between sweep and send.

The email itself is a call to your provider, and the risky moment is a crash after the provider accepted the message but before the row is marked sent. A provider idempotency key built from the reminder key covers it; Resend, for example, drops a repeat request with the same Idempotency-Key within 24 hours.

Abandoned cart reminders are marketing email, and Gmail's sender guidelines require one-click unsubscribe for marketing messages from bulk senders, which is the List-Unsubscribe and List-Unsubscribe-Post: List-Unsubscribe=One-Click pair defined in RFC 8058, plus a visible link in the body. The link carries an HMAC-signed SHA-256 of the address rather than the address itself, so email addresses do not end up in access logs. Consent rules vary, so the sweep only selects carts with marketing_ok; check the rules that apply to your customers with counsel.

Discount codes that work once

The second reminder carries a 10% code, and each cart gets at most one (UNIQUE (cart_id)), so a redelivered step 2 reuses the code instead of minting another. The code expires after 48 hours and is redeemed with a conditional UPDATE that sets the order ID. A retry from checkout with the same order ID succeeds again, and a second order is refused.

How do you build it by hand on AWS?

  1. Consume cart events. The storefront publishes to an SNS topic, and an SQS queue feeds a worker on ECS Fargate that applies the upsert to RDS for PostgreSQL.
  2. Run the sweep. An EventBridge Scheduler rule or an ECS scheduled task runs the insert and publish every 15 minutes, with its own task role and network access to RDS.
  3. Send. A second SNS topic and SQS queue, with a dead-letter queue, feed the sender, which calls Amazon SES or another email provider. If the provider has no idempotency key, the reminders row is the only guard against a duplicate after a crash.
  4. Unsubscribe and codes. An API behind a load balancer serves the unsubscribe POST and the redeem call, with the HMAC key in Secrets Manager.

That is two topics, two queues and their DLQs, a schedule, three compute pieces, IAM for each and a secret, all to keep in sync with the code as steps and templates change.

How do you build it with Encore?

Encore

Encore is a backend framework for Go with built-in infrastructure, and here the cart events topic, the reminders topic, the database, the 15-minute schedule and the signing secret are declared in the same file as the handlers. On deploy to your own AWS account, Encore provisions RDS and SNS with SQS, as the AWS infrastructure docs describe, provisions an IAM role for the service, and the Encore platform calls the sweep on schedule with no extra cloud resources for cron.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

A coding agent asked for a third reminder at 72 hours adds a row to the VALUES list and a step to the CHECK, and encore run gives it Postgres and local Pub/Sub to replay cart events against before the change is reviewed.

Set up the app

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

Run in your terminal to get started locally.

~
$ encore app create cart-recovery --example=hello-world$ cd cart-recovery && mkdir -p carts/migrations$ encore secret set --type dev,local,prod UnsubscribeKey

The secret is set per environment type and never committed, so the key that signs unsubscribe links is not in the repository where a coding agent could read it. The schema goes in carts/migrations/1_carts.up.sql:

CREATE TABLE carts ( id TEXT PRIMARY KEY, email TEXT, -- stored lower-cased marketing_ok BOOLEAN NOT NULL DEFAULT false, total_cents BIGINT NOT NULL DEFAULT 0, last_event_at TIMESTAMPTZ NOT NULL, -- newest event applied, for out-of-order delivery idle_since TIMESTAMPTZ NOT NULL, -- last time the customer changed the cart checked_out_at TIMESTAMPTZ, recovered BOOLEAN NOT NULL DEFAULT false ); CREATE INDEX carts_idle ON carts (idle_since) WHERE checked_out_at IS NULL; -- One row per cart, idle period and step. The primary key is the idempotency key. CREATE TABLE reminders ( cart_id TEXT NOT NULL REFERENCES carts (id), idle_since TIMESTAMPTZ NOT NULL, step INT NOT NULL CHECK (step IN (1, 2)), status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'sent', 'skipped')), published_at TIMESTAMPTZ, -- last time the row was put on the topic sent_at TIMESTAMPTZ, PRIMARY KEY (cart_id, idle_since, step) ); -- SHA-256 of the lower-cased address, so unsubscribe links carry no email. CREATE TABLE unsubscribes ( email_hash TEXT PRIMARY KEY, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE discount_codes ( code TEXT PRIMARY KEY, cart_id TEXT NOT NULL UNIQUE REFERENCES carts (id), percent_off INT NOT NULL CHECK (percent_off BETWEEN 1 AND 50), expires_at TIMESTAMPTZ NOT NULL, redeemed_by TEXT, -- order ID redeemed_at TIMESTAMPTZ );

The carts service

The service consumes cart events, runs the sweep, sends reminders, issues and redeems codes, and handles unsubscribe. The storefront publishes with carts.CartEvents.Publish(ctx, &carts.CartEvent{...}) from its own service:

// carts/carts.go package carts import ( "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base32" "encoding/hex" "errors" "fmt" "net/http" "net/url" "strings" "time" "encore.dev/beta/errs" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/rlog" "encore.dev/storage/sqldb" ) // `encore run` starts Postgres locally; RDS or Cloud SQL in your own account when deployed. var db = sqldb.NewDatabase("carts", sqldb.DatabaseConfig{Migrations: "./migrations"}) var secrets struct { UnsubscribeKey string // signs unsubscribe links } // CartEvent is published by the storefront on every cart change and on checkout. type CartEvent struct { CartID string `json:"cart_id"` Kind string `json:"kind"` // "updated" or "checked_out" Email string `json:"email,omitempty"` MarketingOK bool `json:"marketing_ok"` TotalCents int64 `json:"total_cents"` OccurredAt time.Time `json:"occurred_at"` } var CartEvents = pubsub.NewTopic[*CartEvent]("cart-events", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) var _ = pubsub.NewSubscription(CartEvents, "track-carts", pubsub.SubscriptionConfig[*CartEvent]{ Handler: trackCart, }) // trackCart applies an event only if it is newer than the last one applied, // so a redelivered or late "updated" cannot reopen a checked-out cart, // and a late "checked_out" cannot close a cart that has already moved on. func trackCart(ctx context.Context, e *CartEvent) error { switch e.Kind { case "updated": _, err := db.Exec(ctx, ` INSERT INTO carts (id, email, marketing_ok, total_cents, last_event_at, idle_since) VALUES ($1, lower(NULLIF(trim($2), '')), $3, $4, $5, $5) ON CONFLICT (id) DO UPDATE SET email = COALESCE(EXCLUDED.email, carts.email), marketing_ok = EXCLUDED.marketing_ok, total_cents = EXCLUDED.total_cents, last_event_at = EXCLUDED.last_event_at, idle_since = EXCLUDED.idle_since WHERE carts.checked_out_at IS NULL AND carts.last_event_at < EXCLUDED.last_event_at`, e.CartID, e.Email, e.MarketingOK, e.TotalCents, e.OccurredAt) return err case "checked_out": // Count it as recovered if a reminder went out in the last 7 days. _, err := db.Exec(ctx, ` UPDATE carts SET checked_out_at = $2, last_event_at = GREATEST(last_event_at, $2), recovered = EXISTS ( SELECT 1 FROM reminders r WHERE r.cart_id = carts.id AND r.status = 'sent' AND r.sent_at > $2 - interval '7 days') WHERE id = $1 AND checked_out_at IS NULL AND last_event_at <= $2`, e.CartID, e.OccurredAt) return err } return nil } // Reminder is one email to send. The cart, idle period and step identify it. type Reminder struct { CartID string `json:"cart_id"` IdleSince time.Time `json:"idle_since"` Step int `json:"step"` } var Reminders = pubsub.NewTopic[*Reminder]("cart-reminders", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) // Called by the Encore platform every 15 minutes once deployed. // Cron jobs do not run locally; call QueueDue from the local dashboard instead. var _ = cron.NewJob("queue-cart-reminders", cron.JobConfig{ Title: "Queue abandoned cart reminders", Every: 15 * cron.Minute, Endpoint: QueueDue, }) type QueueResult struct { Queued int `json:"queued"` } // QueueDue inserts a reminder row for every cart that reached a step, then // publishes the rows that are not on the topic yet. The insert is the claim: // overlapping runs and retries hit the primary key and queue nothing twice. // A row whose publish failed is picked up again after ten minutes. // //encore:api private func QueueDue(ctx context.Context) (*QueueResult, error) { _, err := db.Exec(ctx, ` INSERT INTO reminders (cart_id, idle_since, step) SELECT c.id, c.idle_since, s.step FROM carts c -- Step 1 after an hour, step 2 (with a code) after a day, none after a week. CROSS JOIN (VALUES (1, interval '1 hour', interval '24 hours'), (2, interval '24 hours', interval '7 days')) AS s(step, after, until) WHERE c.checked_out_at IS NULL AND c.marketing_ok AND c.email IS NOT NULL AND c.total_cents > 0 AND c.idle_since <= now() - s.after AND c.idle_since > now() - s.until AND NOT EXISTS ( SELECT 1 FROM unsubscribes u WHERE u.email_hash = encode(sha256(convert_to(c.email, 'UTF8')), 'hex')) ON CONFLICT DO NOTHING`) if err != nil { return nil, err } rows, err := db.Query(ctx, ` UPDATE reminders SET published_at = now() WHERE status = 'queued' AND (published_at IS NULL OR published_at < now() - interval '10 minutes') RETURNING cart_id, idle_since, step`) if err != nil { return nil, err } defer rows.Close() var due []*Reminder for rows.Next() { r := &Reminder{} if err := rows.Scan(&r.CartID, &r.IdleSince, &r.Step); err != nil { return nil, err } due = append(due, r) } if err := rows.Err(); err != nil { return nil, err } for _, r := range due { if _, err := Reminders.Publish(ctx, r); err != nil { return nil, err } } return &QueueResult{Queued: len(due)}, nil } var _ = pubsub.NewSubscription(Reminders, "send-cart-reminder", pubsub.SubscriptionConfig[*Reminder]{ Handler: sendReminder, }) func sendReminder(ctx context.Context, r *Reminder) error { // Re-check everything at send time: the customer may have checked out, // changed the cart (new idle period) or unsubscribed since the row was queued. var email string err := db.QueryRow(ctx, ` SELECT c.email FROM reminders r JOIN carts c ON c.id = r.cart_id WHERE r.cart_id = $1 AND r.idle_since = $2 AND r.step = $3 AND r.status = 'queued' AND c.checked_out_at IS NULL AND c.idle_since = r.idle_since AND NOT EXISTS ( SELECT 1 FROM unsubscribes u WHERE u.email_hash = encode(sha256(convert_to(c.email, 'UTF8')), 'hex'))`, r.CartID, r.IdleSince, r.Step).Scan(&email) if errors.Is(err, sqldb.ErrNoRows) { _, err = db.Exec(ctx, ` UPDATE reminders SET status = 'skipped' WHERE cart_id = $1 AND idle_since = $2 AND step = $3 AND status = 'queued'`, r.CartID, r.IdleSince, r.Step) return err } else if err != nil { return err } var code string if r.Step == 2 { if code, err = discountFor(ctx, r.CartID); err != nil { return err } } // The provider deduplicates on this key, so a redelivery after a crash // between sending and the UPDATE below does not send a second email. key := fmt.Sprintf("cart-reminder/%s/%d/%d", r.CartID, r.IdleSince.Unix(), r.Step) rlog.Info("send cart reminder", "cart", r.CartID, "step", r.Step, "idempotency_key", key, "has_code", code != "", "unsubscribe", unsubscribeURL(email)) // Call your email provider here with key as its idempotency key, and set // List-Unsubscribe to unsubscribeURL(email) and List-Unsubscribe-Post to // "List-Unsubscribe=One-Click". _, err = db.Exec(ctx, ` UPDATE reminders SET status = 'sent', sent_at = now() WHERE cart_id = $1 AND idle_since = $2 AND step = $3 AND status = 'queued'`, r.CartID, r.IdleSince, r.Step) return err } var codeEncoding = base32.StdEncoding.WithPadding(base32.NoPadding) // discountFor returns the cart's single discount code, creating it on first use. func discountFor(ctx context.Context, cartID string) (string, error) { b := make([]byte, 5) if _, err := rand.Read(b); err != nil { return "", err } var code string err := db.QueryRow(ctx, ` WITH ins AS ( INSERT INTO discount_codes (code, cart_id, percent_off, expires_at) VALUES ($1, $2, 10, now() + interval '48 hours') ON CONFLICT (cart_id) DO NOTHING RETURNING code ) SELECT code FROM ins UNION ALL SELECT code FROM discount_codes WHERE cart_id = $2 LIMIT 1`, "BACK-"+codeEncoding.EncodeToString(b), cartID).Scan(&code) return code, err } type RedeemParams struct { Code string `json:"code"` OrderID string `json:"order_id"` } type RedeemResult struct { PercentOff int `json:"percent_off"` } // Redeem is called by checkout. A code works once, before it expires, and a // retry with the same order ID gets the same answer. // //encore:api private method=POST path=/discounts/redeem func Redeem(ctx context.Context, p *RedeemParams) (*RedeemResult, error) { var res RedeemResult err := db.QueryRow(ctx, ` UPDATE discount_codes SET redeemed_by = $2, redeemed_at = now() WHERE code = $1 AND expires_at > now() AND (redeemed_by IS NULL OR redeemed_by = $2) RETURNING percent_off`, strings.ToUpper(strings.TrimSpace(p.Code)), p.OrderID).Scan(&res.PercentOff) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "code is invalid, expired or already used"} } return &res, err } // Unsubscribe takes one-click POSTs from mail clients (RFC 8058) and the // form on the storefront page that the link in the email body opens. // //encore:api public raw method=POST path=/unsubscribe func Unsubscribe(w http.ResponseWriter, req *http.Request) { hash, ok := verifyUnsubscribe(req.URL.Query().Get("e"), req.URL.Query().Get("sig")) if !ok { http.Error(w, "invalid unsubscribe link", http.StatusBadRequest) return } if _, err := db.Exec(req.Context(), ` INSERT INTO unsubscribes (email_hash) VALUES ($1) ON CONFLICT DO NOTHING`, hash); err != nil { http.Error(w, "try again", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func unsubscribeURL(email string) string { sum := sha256.Sum256([]byte(email)) // email is already lower-cased hash := hex.EncodeToString(sum[:]) q := url.Values{"e": {hash}, "sig": {sign(hash)}} return "https://api.shop.example.com/unsubscribe?" + q.Encode() } func verifyUnsubscribe(hash, sig string) (string, bool) { if hash == "" || !hmac.Equal([]byte(sig), []byte(sign(hash))) { return "", false } return hash, true } func sign(s string) string { mac := hmac.New(sha256.New, []byte(secrets.UnsubscribeKey)) mac.Write([]byte(s)) return hex.EncodeToString(mac.Sum(nil)) }

The code passes go vet and Encore's compiler, and the SQL was run against Postgres 17: an older event for the same cart was ignored, a second sweep queued nothing, a row with a stale published_at was published again, a cart idle for 30 hours got only step 2, editing a cart made its pending step 1 unsendable, a second request for a code returned the first one, a code redeemed by one order was refused for another, and an "updated" event after checkout left the cart closed. The address hash computed by Postgres matches the one Go puts in the link.

Pub/Sub retries a subscriber that returns an error, so a failed database call in sendReminder is retried rather than lost. Cron jobs do not run locally or in preview environments, so test the sweep by calling QueueDue from the local development dashboard; once deployed, the Encore platform calls it every 15 minutes.

Deploy to your AWS account

Connect your AWS account as described in Connect your cloud account, set UnsubscribeKey for production, and run git push encore. Encore builds the image, creates the database, topics and queues, and wires the subscriptions to the service.

Things to decide early

  • Which carts count. The sweep skips carts with no email, no consent or a zero total. You may also want to skip carts whose items are out of stock, which needs inventory in the event or a lookup at send time.
  • How many steps. This design uses two reminders, and every extra step is another chance for an unsubscribe, so measure recovery per step with the recovered flag before adding a third.
  • What the code is worth. A discount on a later reminder can train customers to wait for the code, so treat the amount as a business choice. Some shops only send a code to first-time buyers or above a cart total.
  • Retention. reminders and carts grow with traffic, so delete carts that checked out or went idle more than 30 days ago, and keep unsubscribes indefinitely.

Frequently asked questions

How do you detect an abandoned cart?

Keep an idle_since timestamp on each cart that moves forward on every change, and treat a cart as abandoned when it has an email, consent and items, has not checked out, and idle_since is older than your first delay, often one hour. A scheduled sweep finds those carts instead of a timer per cart.

How do you stop abandoned cart emails from being sent twice?

Give every reminder a natural key of cart, idle period and step, insert it with ON CONFLICT DO NOTHING so the insert is the claim, and mark it sent with a conditional UPDATE. Pass the same key to your email provider as an idempotency key so a retry after a crash between sending and marking is deduplicated.

Do abandoned cart emails need an unsubscribe link?

Yes, since they are marketing email, and Gmail requires bulk senders to support one-click unsubscribe for marketing messages, which means List-Unsubscribe and List-Unsubscribe-Post headers as described in RFC 8058, plus a visible link in the body. In many jurisdictions they also need prior marketing consent, so check with counsel.

How do you build abandoned cart reminders with Encore?

Declare the cart events topic, the reminders topic, the database, the unsubscribe signing secret and a cron job with Every: 15 * cron.Minute in Go. The sweep inserts reminder rows and publishes them, a subscription re-checks the cart and sends, and deploys provision RDS, SNS and SQS in your own AWS account while the Encore platform runs the cron schedule.

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