Nov 23, 20268 min read

Build a Subscription Box Backend for an Online Store

How to run monthly box cycles with a cutoff date, skips and pauses, one charge per subscriber per cycle and order creation that survives retries, built with Encore cron, Pub/Sub and Postgres.

Illustration for Build a Subscription Box Backend for an Online Store

A subscription box is a monthly promise: pick what ships, charge the card once, and get the box out the door. The code that backs it is a calendar, a cutoff date after which nothing changes, and a set of rules about skips, pauses and failed cards.

The calendar breaks first, since a billing date of the 31st does not exist in most months. This guide designs the cycle model, then builds it with Encore.

The box backend at a glance

JobPatternWhat goes wrong without it
CyclesOne row per cycle with a cutoff timeChanges arrive after picking starts
Billing datesAnchor day plus month arithmetic that clampsSubscribers skip a month or get charged early
Skips and pausesAccepted until the cutoffSupport tickets for boxes that should not ship
Order creationUnique on subscription and cycleTwo boxes for one payment
ChargingIdempotency key per subscription and cycleDouble charges after retries
Failed cardsRetry, then hold the boxBoxes shipped unpaid

Why does the cutoff drive the design?

Warehouses need a fixed list on a fixed day. A cycle row with a cutoff_at timestamp gives every rule one reference point: skips, pauses, plan changes and address updates are accepted before it and apply to the next cycle after it. At the cutoff a job reads every active subscription, ignores the skipped ones and inserts one box order each, which is the list the warehouse picks.

Billing can run at the cutoff or a few days before it. Charging first and shipping only paid orders is the simpler rule, and the Stripe subscriptions overview covers the provider-side lifecycle if you let the provider own the schedule.

How do you compute the next billing date?

Adding a month to the 31st is the classic bug. Go's AddDate normalizes the result, so January 31 plus one month becomes March 3. PostgreSQL's interval arithmetic clamps to the last day of the month instead, giving February 28.

Store the subscriber's anchor day, for example the 31st, and compute each cycle's date from the anchor and the month, clamped to the month's length. Computing from the anchor every time avoids drifting from the 31st to the 28th after one short month.

How do you charge once per cycle?

A box order is unique on (subscription_id, cycle_id), so a second run of the cutoff job inserts nothing. The charge uses an idempotency key built from the same pair, so a crash between the provider call and the database write repeats the request with the same key and gets the original result. The same pattern is covered in API idempotency keys, and failed payments follow the dunning flow.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and the box service declares its Postgres database, the payment key as a secret, an order Pub/Sub topic and a daily cron job in code, and provisions them in your AWS or GCP account.

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.

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 boxes --example=hello-world$ cd boxes && mkdir -p boxes/migrations$ encore secret set --type dev,local,pr StripeSecretKey$ encore secret set --type prod StripeSecretKey

Use a test-mode key outside production. The secret values are stored by Encore, not in the repository.

The schema

-- boxes/migrations/1_create_boxes.up.sql CREATE TABLE subscriptions ( id BIGSERIAL PRIMARY KEY, customer_id TEXT NOT NULL, psp_customer_id TEXT NOT NULL, payment_method TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active', -- active | paused | cancelled amount_cents BIGINT NOT NULL, currency TEXT NOT NULL DEFAULT 'usd' ); CREATE TABLE cycles ( id BIGSERIAL PRIMARY KEY, ship_month DATE NOT NULL UNIQUE, -- first day of the month cutoff_at TIMESTAMPTZ NOT NULL, closed_at TIMESTAMPTZ ); CREATE TABLE skips ( subscription_id BIGINT NOT NULL REFERENCES subscriptions(id), cycle_id BIGINT NOT NULL REFERENCES cycles(id), PRIMARY KEY (subscription_id, cycle_id) ); CREATE TABLE box_orders ( id BIGSERIAL PRIMARY KEY, subscription_id BIGINT NOT NULL REFERENCES subscriptions(id), cycle_id BIGINT NOT NULL REFERENCES cycles(id), status TEXT NOT NULL DEFAULT 'created', -- created | paid | payment_failed charge_id TEXT, UNIQUE (subscription_id, cycle_id) );

The service

// boxes/boxes.go package boxes import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "strings" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("boxes", sqldb.DatabaseConfig{ Migrations: "./migrations", }) var secrets struct { StripeSecretKey string } type OrderCreated struct { OrderID int64 } var Orders = pubsub.NewTopic[*OrderCreated]("box-orders", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) // Skip is accepted only while the cycle is open. // //encore:api private method=POST path=/subscriptions/:id/skip/:cycleID func Skip(ctx context.Context, id, cycleID int64) error { _, err := db.Exec(ctx, ` INSERT INTO skips (subscription_id, cycle_id) SELECT $1, c.id FROM cycles c WHERE c.id = $2 AND c.cutoff_at > now() ON CONFLICT DO NOTHING`, id, cycleID) return err } // CloseCycles turns every active, unskipped subscriber into one order for each // cycle past its cutoff, publishes the orders that are not paid yet and then // marks the cycle closed. Running it twice creates no extra orders, and a failed // publish is retried on the next run because the cycle is still open. // //encore:api private method=POST path=/cycles/close func CloseCycles(ctx context.Context) error { if _, err := db.Exec(ctx, ` INSERT INTO box_orders (subscription_id, cycle_id) SELECT s.id, c.id FROM subscriptions s CROSS JOIN cycles c WHERE c.closed_at IS NULL AND c.cutoff_at <= now() AND s.status = 'active' AND NOT EXISTS (SELECT 1 FROM skips k WHERE k.subscription_id = s.id AND k.cycle_id = c.id) ON CONFLICT (subscription_id, cycle_id) DO NOTHING`); err != nil { return err } rows, err := db.Query(ctx, ` SELECT o.id FROM box_orders o JOIN cycles c ON c.id = o.cycle_id WHERE c.closed_at IS NULL AND c.cutoff_at <= now() AND o.status = 'created'`) if err != nil { return err } var ids []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { rows.Close() return err } ids = append(ids, id) } rows.Close() for _, id := range ids { if _, err := Orders.Publish(ctx, &OrderCreated{OrderID: id}); err != nil { return err } } _, err = db.Exec(ctx, `UPDATE cycles SET closed_at = now() WHERE closed_at IS NULL AND cutoff_at <= now()`) return err } var _ = pubsub.NewSubscription(Orders, "charge-box", pubsub.SubscriptionConfig[*OrderCreated]{ Handler: func(ctx context.Context, m *OrderCreated) error { var ( subID, cycleID, amount int64 currency, cust, method, status string ) err := db.QueryRow(ctx, ` SELECT o.subscription_id, o.cycle_id, s.amount_cents, s.currency, s.psp_customer_id, s.payment_method, o.status FROM box_orders o JOIN subscriptions s ON s.id = o.subscription_id WHERE o.id = $1`, m.OrderID).Scan(&subID, &cycleID, &amount, &currency, &cust, &method, &status) if err != nil { return err } if status == "paid" { return nil // a repeated message } form := url.Values{ "amount": {fmt.Sprint(amount)}, "currency": {currency}, "customer": {cust}, "payment_method": {method}, "off_session": {"true"}, "confirm": {"true"}, } req, _ := http.NewRequestWithContext(ctx, "POST", "https://api.stripe.com/v1/payment_intents", strings.NewReader(form.Encode())) req.Header.Set("Authorization", "Bearer "+secrets.StripeSecretKey) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") // The same key for the same box, so a retry cannot charge twice. req.Header.Set("Idempotency-Key", fmt.Sprintf("box-%d-%d", subID, cycleID)) resp, err := http.DefaultClient.Do(req) if err != nil { return err // retried by the subscription } defer resp.Body.Close() var body struct { ID string `json:"id"` Status string `json:"status"` } if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { return err } switch { case resp.StatusCode >= 500 || resp.StatusCode == 429: return errors.New("payment provider unavailable") case resp.StatusCode == 200 && body.Status == "succeeded": _, err = db.Exec(ctx, `UPDATE box_orders SET status = 'paid', charge_id = $2 WHERE id = $1`, m.OrderID, body.ID) case resp.StatusCode == 402: // A declined card holds the subscription, so the next cycle creates no unpaid box. // A dunning job retries the charge and sets it back to active once it succeeds. _, err = db.Exec(ctx, `UPDATE box_orders SET status = 'payment_failed' WHERE id = $1`, m.OrderID) if err == nil { _, err = db.Exec(ctx, `UPDATE subscriptions SET status = 'paused' WHERE id = $1`, subID) } default: // Auth or request errors are ours to fix, not the customer's: retry, then dead-letter. return fmt.Errorf("payment provider returned %d", resp.StatusCode) } return err }, }) // Managed by the Encore platform in deployed environments. It does not run // under `encore run`, so call CloseCycles directly when testing locally. var _ = cron.NewJob("close-cycles", cron.JobConfig{ Title: "Close cycles past their cutoff", Every: 1 * cron.Hour, Endpoint: CloseCycles, })

encore run starts a local Postgres, applies the migration and serves the endpoints, so a test can insert a cycle with a past cutoff, call CloseCycles twice and check that each subscriber has one order. The cron job is managed by the Encore platform and does not run locally or in preview environments. On deploy, the database runs on RDS or Cloud SQL and the topic on SNS and SQS or GCP Pub/Sub, and Encore provisions an IAM role for the service.

A coding agent adding a warehouse export subscribes to box-orders in the same change and runs it locally, with no queue to create and no permissions to wire up separately.

Best fit: Teams running a recurring box or replenishment product who want the cycle rules and their infrastructure in one repository.

How would you build it by hand?

On AWS the same service needs an RDS database, a container deployment, an EventBridge Scheduler rule for the hourly job, an SNS topic with an SQS queue for the charge consumer, the payment key in Secrets Manager and IAM for each piece, in Terraform. The Go stays close to the code above, and the extra work is the infrastructure definitions and a local setup that matches them.

Things to decide early

  • Charge timing. Decide whether to charge at the cutoff or a few days earlier, and how long a failed card holds a box before you give up.
  • Pauses. Treat a pause as a skip with no end date, and make the resume date explicit.
  • Plan changes. Apply a change at the next cycle, never to a cycle that has already closed.
  • Stock shortages. Decide whether a short SKU delays the box, substitutes an item or splits the shipment, and record the choice on the order.

Frequently asked questions

How do you model a subscription box cycle?

Create a row per cycle with a cutoff time and a ship month, and a row per subscriber and cycle that records the outcome. Skips, pauses and address changes are accepted until the cutoff, and a job at the cutoff turns every active, unskipped subscriber into exactly one box order.

How do you avoid charging a subscriber twice for one box?

Make the box order unique on subscription and cycle, and send the payment provider an idempotency key built from the same two IDs. A retry after a crash then returns the first charge result instead of creating a second charge.

How do you add one month to a billing date correctly?

Do not add 30 days, and be careful with calendar arithmetic. Adding one month to January 31 gives March 3 with Go's AddDate, which normalizes the overflow, while PostgreSQL clamps the same addition to February 28. Store the anchor day and compute each cycle from it.

How do you build a subscription box backend with Encore?

With Encore, declare the Postgres database, the payment key as a secret, an order topic and a daily cron job next to the handlers. Encore provisions the database and topic in your AWS or GCP account, and the cron job is managed by the Encore platform.

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