Nov 23, 20269 min read

Build Back-in-Stock Notifications for an Online Store

Design the backend behind "notify me when available": signups without duplicates, detecting the moment a variant comes back, notifying in waves sized to the stock so 5,000 people do not chase 20 units, one-click unsubscribe, with a TypeScript example.

Illustration for Build Back-in-Stock Notifications for an Online Store

"Notify me when available" is one of the cheaper ways to recover a lost sale, since the shopper already picked the product and only the stock was missing. Done carelessly, it also creates angry customers: twenty units, five thousand emails, and most people click through to a sold-out page again.

This guide builds the backend for it, from signups and restock detection to waves sized to stock and unsubscribe, with TypeScript code using Encore.

The Back-in-Stock Backend at a Glance

PieceWhat it doesBuilt with
SignupsOne waiting alert per email and variantPostgres
Restock detectionFires when stock goes from zero to positiveInventory service
Restock eventTells the alerts service a variant is backPub/Sub
Notification wavesEmails the oldest signups, sized to stockAPI and cron
UnsubscribeOne-click cancel from the emailAPI endpoint

Why Notify in Waves?

The obvious implementation emails everyone on the list when stock arrives. With a long list and a small restock that turns into a race, and every shopper who loses it gets the same disappointment that made them sign up. A wave sized to stock, such as three signups per unit, gives the oldest signups a fair chance, and a later wave goes out only if units remain.

Waves also protect your sending reputation, since Gmail's sender guidelines require senders of more than 5,000 messages a day to support one-click unsubscribe on marketing and subscribed messages, and a sudden burst of emails to old signups is the kind of traffic that draws complaints.

Detecting the Restock

Back in stock means a transition, not a state: stock was zero and is now positive. Detecting it where stock is written, in the same statement, avoids both missed restocks and repeated alerts for every later stock change. If inventory lives in a commerce platform, its inventory webhooks, such as the inventory_levels/update topic in Shopify's webhook reference, feed the same logic.

Building It with Encore

Encore

Encore is a backend framework with built-in infrastructure: the two databases, the restock topic, the wave schedule and the email provider key below are declared in TypeScript. encore run starts them locally, and deploying creates them in your own AWS or GCP account. The inventory and alerts folders each have an encore.service.ts that declares the service.

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

Run in your terminal to get started locally.

Inventory Publishes the Restock

// inventory/inventory.ts import { api, APIError } from "encore.dev/api"; import { Topic } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; // migrations/1_create_variants.up.sql: // CREATE TABLE variants (id text PRIMARY KEY, product_name text NOT NULL, // stock integer NOT NULL CHECK (stock >= 0)); const db = new SQLDatabase("inventory", { migrations: "./migrations" }); export interface Restocked { variantId: string; productName: string; stock: number; } export const restocked = new Topic<Restocked>("variant-restocked", { deliveryGuarantee: "at-least-once", }); export const setStock = api( { method: "PUT", path: "/inventory/:variantId/stock" }, async ({ variantId, stock }: { variantId: string; stock: number }): Promise<void> => { if (stock < 0) { throw APIError.invalidArgument("stock must be zero or more"); } // Lock the row and read the old value in the same statement as the update. const row = await db.queryRow<{ before: number; product_name: string }>` WITH old AS (SELECT id, stock FROM variants WHERE id = ${variantId} FOR UPDATE) UPDATE variants v SET stock = ${stock} FROM old WHERE v.id = old.id RETURNING old.stock AS before, v.product_name `; if (!row) { throw APIError.notFound("unknown variant"); } if (row.before === 0 && stock > 0) { await restocked.publish({ variantId, productName: row.product_name, stock }); } }, ); export const getStock = api( { method: "GET", path: "/inventory/:variantId/stock" }, async ({ variantId }: { variantId: string }): Promise<{ stock: number }> => { const row = await db.queryRow<{ stock: number }>`SELECT stock FROM variants WHERE id = ${variantId}`; return { stock: row?.stock ?? 0 }; }, );

FOR UPDATE in the CTE makes two concurrent stock updates take turns, so only one of them sees before = 0 and publishes. Both endpoints are internal, called by other services through generated clients rather than from the internet.

Signups and Unsubscribe

-- alerts/migrations/1_create_alerts.up.sql CREATE TABLE stock_alerts ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, variant_id text NOT NULL, product_name text NOT NULL, email text NOT NULL, unsubscribe_token uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE, created_at timestamptz NOT NULL DEFAULT now(), notified_at timestamptz, cancelled_at timestamptz ); -- One waiting alert per email and variant; a notified shopper can sign up again. CREATE UNIQUE INDEX stock_alerts_one_waiting ON stock_alerts (variant_id, lower(email)) WHERE notified_at IS NULL AND cancelled_at IS NULL; CREATE INDEX stock_alerts_queue ON stock_alerts (variant_id, created_at) WHERE notified_at IS NULL AND cancelled_at IS NULL;
// alerts/signups.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; export const db = new SQLDatabase("alerts", { migrations: "./migrations" }); interface SignupParams { variantId: string; productName: string; email: string; } export const signup = api( { expose: true, method: "POST", path: "/variants/:variantId/stock-alerts" }, async ({ variantId, productName, email }: SignupParams): Promise<{ ok: boolean }> => { const clean = email.trim(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(clean) || clean.length > 254) { throw APIError.invalidArgument("invalid email address"); } // A repeat signup is a no-op, and the response is the same either way. await db.exec` INSERT INTO stock_alerts (variant_id, product_name, email) VALUES (${variantId}, ${productName}, ${clean}) ON CONFLICT (variant_id, lower(email)) WHERE notified_at IS NULL AND cancelled_at IS NULL DO NOTHING `; return { ok: true }; }, ); // Target of the List-Unsubscribe header and the link in the email body. export const unsubscribe = api( { expose: true, method: "POST", path: "/stock-alerts/unsubscribe/:token" }, async ({ token }: { token: string }): Promise<{ ok: boolean }> => { await db.exec` UPDATE stock_alerts SET cancelled_at = now() WHERE unsubscribe_token::text = ${token} AND cancelled_at IS NULL `; return { ok: true }; }, );

Returning the same response for new and repeat signups keeps the endpoint from revealing which emails are on a list. Unsubscribe is a POST, because RFC 8058 one-click unsubscribe works by the mail client posting to the URL in List-Unsubscribe, and a GET would let link scanners cancel alerts by visiting them.

Notification Waves

// alerts/waves.ts import { api } from "encore.dev/api"; import { secret } from "encore.dev/config"; import { CronJob } from "encore.dev/cron"; import log from "encore.dev/log"; import { Subscription } from "encore.dev/pubsub"; import { inventory } from "~encore/clients"; import { restocked } from "../inventory/inventory"; import { db } from "./signups"; const emailApiKey = secret("EmailApiKey"); const SIGNUPS_PER_UNIT = 3; const MAX_WAVE = 500; async function sendWave(variantId: string, stock: number): Promise<number> { // Signups emailed in the last two hours still have a claim on this stock, // so they count against the wave instead of being offered the same units again. const recent = await db.queryRow<{ n: number }>` SELECT count(*)::int AS n FROM stock_alerts WHERE variant_id = ${variantId} AND notified_at > now() - interval '2 hours'`; const limit = Math.min(stock * SIGNUPS_PER_UNIT - (recent?.n ?? 0), MAX_WAVE); if (limit <= 0) return 0; // Claim the oldest waiting signups. SKIP LOCKED lets an overlapping wave // take the next ones instead of the same ones. const claimed = db.query<{ id: number; email: string; product_name: string; unsubscribe_token: string }>` UPDATE stock_alerts SET notified_at = now() WHERE id IN ( SELECT id FROM stock_alerts WHERE variant_id = ${variantId} AND notified_at IS NULL AND cancelled_at IS NULL ORDER BY created_at LIMIT ${limit} FOR UPDATE SKIP LOCKED ) RETURNING id, email, product_name, unsubscribe_token::text `; let sent = 0; for await (const a of claimed) { try { await sendEmail(a.email, a.product_name, variantId, a.unsubscribe_token); sent++; } catch (err) { // Put the signup back in the queue for the next wave. await db.exec`UPDATE stock_alerts SET notified_at = NULL WHERE id = ${a.id}`; log.error(err, "back-in-stock email failed", { variantId }); } } return sent; } async function sendEmail(to: string, product: string, variantId: string, token: string) { const unsubscribeURL = `https://shop.example.com/api/stock-alerts/unsubscribe/${token}`; const res = await fetch("https://email.example.com/v1/send", { method: "POST", headers: { Authorization: `Bearer ${emailApiKey()}`, "Content-Type": "application/json" }, body: JSON.stringify({ to, subject: `${product} is back in stock`, text: `Get it here: https://shop.example.com/v/${variantId}\nStop these alerts: ${unsubscribeURL}`, headers: { "List-Unsubscribe": `<${unsubscribeURL}>`, "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", }, }), }); if (!res.ok) { throw new Error(`email provider returned ${res.status}`); } } // First wave, as soon as inventory reports the restock. new Subscription(restocked, "first-wave", { handler: async (e) => { await sendWave(e.variantId, e.stock); }, }); // Later waves, while there is stock left and people waiting. export const nextWaves = api({}, async (): Promise<{ sent: number }> => { const waiting = await db.queryAll<{ variant_id: string }>` SELECT DISTINCT variant_id FROM stock_alerts WHERE notified_at IS NULL AND cancelled_at IS NULL `; let sent = 0; for (const { variant_id } of waiting) { const { stock } = await inventory.getStock({ variantId: variant_id }); if (stock > 0) { sent += await sendWave(variant_id, stock); } } return { sent }; }); new CronJob("back-in-stock-waves", { title: "Send the next wave of back-in-stock emails", every: "30m", endpoint: nextWaves, });

A duplicate restock event cannot double-email anyone, because each wave only claims signups that are still waiting. If the first wave sells the variant out, the next cron run finds stock = 0 and sends nothing, and the remaining shoppers stay on the list for the next restock. A failed email puts its signup back in the queue rather than losing it.

The Pub/Sub docs cover the restock subscription, and the cron job is managed by the Encore platform and runs in deployed environments, not under encore run or in preview environments. Locally you call setStock and then nextWaves from the local development dashboard and watch the claimed rows in the alerts database.

On AWS, the databases run on RDS and the topic on SNS with SQS in your own account, and Encore provisions an IAM role for the service, or a service account on GCP, as the AWS infrastructure docs describe. Groupon reports a 3x increase in development speed, as its case study describes. Changing the wave size per product, say a higher ratio for low-conversion items, is a column and one line in sendWave, which a coding agent can add and test against the local databases in the same change.

Best fit: online stores and marketplaces that want restock alerts which convert without overpromising, running in their own AWS or GCP account.

Things to Decide Early

  • Wave ratio. Start with a few signups per unit and tune it from the conversion of past waves.
  • Reserved stock. Some stores hold units for the alert audience for a short window; decide before marketing promises it.
  • Signup expiry. An alert from a year ago converts poorly, so expire old signups or ask them to confirm.
  • Consent. A waitlist signup is consent to one alert, so treat marketing consent as a separate opt-in and check the rules where you sell.
  • Variant changes. When a variant is discontinued, cancel its waiting alerts and offer the replacement instead.

Frequently asked questions

How do back-in-stock notifications work?

A shopper leaves an email on a sold-out variant, and when inventory moves from zero to a positive number, the store emails waiting shoppers, oldest signup first, and marks each signup as notified so nobody gets the same alert twice.

Should I notify everyone on the waitlist when a product is restocked?

No. If 5,000 people wait for 20 units, emailing all of them at once sells out in minutes and leaves most with a broken promise. Notify in waves sized to the stock, for example three signups per unit, and send the next wave only if stock is still available.

Do back-in-stock emails need an unsubscribe link?

Yes. Gmail requires one-click unsubscribe for marketing and subscribed messages from senders above 5,000 messages a day, and a cancel link is good practice for any waitlist email. RFC 8058 describes the List-Unsubscribe-Post header that enables it.

How do I run the notification waves with Encore?

Inventory publishes a restock event to a Pub/Sub topic, a subscription sends the first wave, and a cron job sends later waves while stock lasts. Encore cron jobs are managed by the Encore platform and run in deployed environments, not locally or in preview environments, so locally you call the wave endpoint directly.

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