
Abandoned Cart Email System: Architecture, Data Model and Pitfalls
An abandoned cart email system looks simple from the outside: someone leaves a checkout, you send a reminder. Underneath it is a small distributed system with timers, webhooks, races against real purchases, consent rules and signed links into a live cart. This deep dive covers how to design an abandoned cart email system that does not email people who already paid, does not send the same message twice and does not leak cart data through a URL. If you want the marketing side (why shoppers leave, what to fix in checkout, which sequence to send), read our 7-step guide to abandoned cart recovery. Here we focus on the engineering.
What the system actually has to do
Before picking tools, write the requirements as behaviors. A production-grade recovery flow must:
- Detect that a cart or checkout is abandoned, using a definition you can explain (inactivity window, explicit expiry, or both).
- Schedule a sequence of messages at fixed offsets from that moment, sometimes hours or days later.
- Suppress every pending message the instant the customer buys, empties the cart, unsubscribes or withdraws consent.
- Send each message at most once, even when workers crash and webhooks are retried.
- Restore the cart from a link, with current prices and stock, without exposing personal data.
- Attribute the resulting order back to the sequence so you can measure it.
Each of these is a place where a naive implementation breaks. The rest of this article goes through them in order.
Data model: carts, events and scheduled messages
Keep three concepts separate: the cart (current state), the events that happened to it (history), and the recovery messages (work to do). Mixing them, for example by putting a reminder_sent boolean on the cart, makes multi-step sequences and audits painful.
CREATE TABLE carts (
id UUID PRIMARY KEY,
customer_id UUID NULL,
email TEXT NULL,
status TEXT NOT NULL, -- active | abandoned | converted | emptied
referrer_id UUID NULL, -- affiliate / distributor attribution
last_activity_at TIMESTAMPTZ NOT NULL,
converted_order_id UUID NULL,
version INT NOT NULL DEFAULT 0 -- bumped on every cart change
);
CREATE TABLE recovery_messages (
id UUID PRIMARY KEY,
cart_id UUID NOT NULL REFERENCES carts(id),
step SMALLINT NOT NULL, -- 1, 2, 3 in the sequence
send_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL, -- pending | sending | sent | cancelled | failed
cart_version INT NOT NULL, -- cart version the message was planned for
provider_message_id TEXT NULL,
attempts SMALLINT NOT NULL DEFAULT 0,
UNIQUE (cart_id, step) -- one message per step, enforced by the DB
);
CREATE INDEX recovery_due ON recovery_messages (send_at)
WHERE status = 'pending';
Two details do most of the work. The UNIQUE (cart_id, step) constraint makes scheduling idempotent: if the abandonment event arrives twice, the second insert fails harmlessly. The cart_version column lets the sender detect that the cart changed after the message was planned, so it can re-plan instead of describing items the customer already removed.
Store consent separately (customer, channel, source, timestamp), not as a column on the cart. You will need to prove when and how consent was given, and it outlives any single cart.
Detecting abandonment: three approaches
1. Inactivity window on your own data. Every cart write updates last_activity_at. A periodic job marks carts as abandoned when they are active, have a reachable email and have been idle longer than your threshold. This works with any stack and gives you full control, but it depends on capturing the email early in checkout, and the threshold is a product decision you have to own.
2. Provider expiry events. If you use a hosted checkout, the provider may already define abandonment for you. In Stripe Checkout, a session becomes abandoned when it reaches its expires_at timestamp and the customer has not completed checking out; Stripe then fires the checkout.session.expired webhook, and you enable recovery with after_expiration.recovery when you create the session. The trade-off: the timing is tied to the session expiry, and the email you can use depends on the consent you collected (see the consent section below).
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: items,
success_url: successUrl,
after_expiration: {
recovery: { enabled: true, allow_promotion_codes: false },
},
consent_collection: { promotions: "auto" },
metadata: { cart_id: cart.id },
});
3. Hybrid. Use your own inactivity rule for carts that never reach payment, and the provider event for checkouts that started payment and expired. Put cart_id in the provider metadata so both paths converge on the same cart row and the same unique constraint.
For most custom stores the hybrid is the right answer: the provider knows about payment state, your app knows about everything that happened before.
Scheduling: delayed queues, schedulers or a database table
Recovery sequences need delays measured in hours or days, which rules out some obvious tools.
- Delayed queue messages. Convenient, but limited. On Amazon SQS, the maximum delay is 15 minutes, so a 24-hour reminder needs chaining or another tool. Messages already in a queue are also hard to cancel.
- Managed one-time schedulers. AWS's own guidance for longer delays is to use EventBridge Scheduler to schedule a task that later sends to a queue or invokes a function. Good scale, but cancellation means deleting schedules, and your source of truth ends up split between the scheduler and your database.
- Database-backed scheduler. The
recovery_messagestable is the schedule. A worker polls for due rows. Cancellation is a singleUPDATE, the state is queryable, and it is easy to test. The cost is polling load and the need for safe concurrent claiming.
For the volumes most stores handle, the database table is usually the simplest correct choice, and you can still hand the actual send to a queue. Claim rows with FOR UPDATE SKIP LOCKED so several workers never pick the same message:
UPDATE recovery_messages
SET status = 'sending', attempts = attempts + 1
WHERE id IN (
SELECT id FROM recovery_messages
WHERE status = 'pending' AND send_at <= now()
ORDER BY send_at
LIMIT 100
FOR UPDATE SKIP LOCKED
)
RETURNING id, cart_id, step, cart_version;
Reference architecture for an abandoned cart email system
Putting the pieces together, a robust layout looks like this:
- Cart service writes cart changes and appends events (
cart.updated,checkout.started,order.created) to an outbox table in the same transaction. - Outbox relay publishes those events to your bus or queue. The outbox pattern guarantees you never commit an order without its event, or publish an event for a rolled-back order.
- Abandonment detector (the periodic job plus the provider webhook handler) marks carts abandoned and inserts the sequence rows.
- Suppression consumer listens to
order.created,cart.emptiedand consent changes and cancels pending messages. - Sender worker claims due rows, re-checks everything, renders the template and calls the email provider.
- Recovery endpoint validates the link token and restores the cart.
The sender's re-check is the most important line of defense. Events can be late; the check at send time cannot:
for msg in claim_due_messages():
cart = load_cart(msg.cart_id)
if cart.status != 'abandoned': cancel(msg); continue
if has_order_since(cart, msg.created_at): cancel(msg); continue
if not has_marketing_consent(cart.email): cancel(msg); continue
if cart.version != msg.cart_version: replan(msg, cart); continue
if cart_is_empty_or_unavailable(cart): cancel(msg); continue
result = email.send(
template = step_template(msg.step),
to = cart.email,
idempotency_key = "cart-recovery:" + msg.id,
link = recovery_link(cart.id, msg.id),
)
mark_sent(msg, result.provider_message_id)
Failure handling and idempotency
Every boundary in this system is at-least-once, so design every step to tolerate repeats.
- Webhooks arrive twice or out of order. Store processed event IDs and rely on the unique constraint for scheduling. Never assume
checkout.session.expiredarrives before or after a related payment event; always read current state. - Worker crashes after sending, before marking sent. The row stays in
sending. A reaper returns stalesendingrows topending, and the idempotency key (or provider message ID lookup) prevents a second email where the provider supports it. Where it does not, accept that a rare duplicate is possible and keep the window small. - Purchase during send. The re-check narrows the race but cannot remove it entirely. Keep templates honest about this ("if you already completed your order, ignore this message") rather than pretending the race does not exist.
- Provider outages. Retry with backoff and a cap on attempts. Do not send step 1 after step 2's time has passed; skip stale steps instead of firing them in a burst.
- Timezones and quiet hours. Compute
send_atin UTC but apply the recipient's local quiet hours when known, so a "reminder" does not land at 3 a.m.
Recovery links: security and cart restoration
The link in the email is an authenticated entry point into a cart, so treat it like one.
- Use an opaque, signed token (HMAC over
cart_id,message_idand an expiry), or a random token stored hashed in the database. Never put the email address, customer ID or cart contents in the query string. - Make tokens expire and scope them to restoring that cart only. A recovery link should not log someone into their account.
- On restore, re-price and re-validate stock. The cart snapshot is from the past; prices, promotions and availability may have changed. Show the customer what changed instead of silently honoring old prices.
- If you use the provider's recovery URL (Stripe exposes
after_expiration.recovery.urlon the expired session), still route it through your own redirect so you can track clicks and handle expired links gracefully. - Record the
message_idon the resulting order. That is how you attribute recovered revenue to a specific step without guessing from UTM parameters alone.
Consent and deliverability are part of the design
Recovery emails are usually treated as marketing messages, so the data model needs consent per channel with source and timestamp, and every message needs a working unsubscribe that flows back into the suppression consumer. Stripe's abandoned cart guide ties recovery emails to collecting promotional consent in Checkout, which is why the snippet above sets consent_collection.promotions. Rules differ between the United States, Mexico, Colombia and other markets, so have someone qualified confirm the requirements for where you sell; your job as an engineer is to make consent explicit, stored and enforced at send time.
A note for network marketing stores
In network marketing, a cart often carries attribution: the distributor who shared the link, a replicated site, or a sponsor ID that drives commissions. Recovery must preserve that. Store referrer_id on the cart at creation, carry it through the recovery token, and make sure the restored order credits the same distributor. Decide explicitly whether a distributor can see or trigger reminders for their own customers, and keep company-sent recovery emails from conflicting with distributor outreach. Platforms built for the industry, like Ariani, our network marketing platform, treat this attribution as part of the order model rather than an afterthought.
Implementation checklist
- Clear abandonment definition, documented and configurable.
- Email captured early in checkout, with consent stored per channel.
UNIQUE (cart_id, step)or equivalent idempotent scheduling.- Outbox or equivalent so order events are never lost.
- Suppression on purchase, empty cart, unsubscribe and consent withdrawal.
- State re-check immediately before every send.
- Concurrency-safe claiming (
SKIP LOCKED, leases or a queue). - Reaper for stuck
sendingrows; capped retries with backoff. - Signed, expiring, PII-free recovery tokens.
- Re-pricing and stock validation on restore.
- Attribution of orders to message and step, plus referrer preservation.
- Metrics: scheduled, cancelled (by reason), sent, clicked, recovered.
Common mistakes
- A boolean instead of a sequence.
reminder_sent = truecannot represent three steps, cancellations or re-planning. - Trusting events over state. Suppression by event alone fails when the
order.createdevent is delayed. Always re-read state before sending. - Emailing paid customers. Usually caused by matching orders to carts by email instead of by
cart_idcarried through checkout metadata. - Leaky links. Email addresses or cart IDs in plain query strings end up in analytics tools and logs.
- Honoring stale prices. Restoring a snapshot without re-validation creates support tickets and margin loss.
- No cancellation reasons. Without them you cannot tell whether the system works or is quietly suppressing everything.
If you are building this into an existing store or platform and want a second pair of eyes on the architecture, our team does this kind of work as part of our custom software development projects.
Frequently asked questions
Should I build an abandoned cart email system or use my email platform's built-in flow?
If your store runs on a platform that already tracks carts and orders, its built-in flow is often enough. Build your own when carts live in your own backend, when you need custom attribution (for example distributor or affiliate credit), or when you need guarantees about suppression and idempotency that the off-the-shelf flow does not give you.
How do I stop recovery emails after a customer buys?
Use two layers: a consumer that cancels pending messages when an order is created for that cart, and a state check in the sender right before each message goes out. Match orders to carts by an ID carried through checkout, not by email address.
Is a cron job good enough for scheduling reminders?
Yes, for most volumes. A cron or worker polling a table of due messages, with concurrency-safe claiming, is simple, cancellable and easy to inspect. Move to a managed scheduler or queue when polling load or volume justifies the extra moving parts.
Comments
No comments yet. Be the first to share what you think.


