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.

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.
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.
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.
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.
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.

Run in your terminal to get started locally.
Use a test-mode key outside production. The secret values are stored by Encore, not in the repository.
-- 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)
);
// 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, ¤cy, &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.
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.
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.
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.
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.
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.