Nov 23, 202612 min read

Build a Scheduled Transfers Backend for a Banking App

Design the backend behind standing orders and scheduled payments: a schema that survives edits and cancellations, monthly dates that do not drift, business day handling, exactly one payment per due date, and a nightly job declared in application code.

Illustration for Build a Scheduled Transfers Backend for a Banking App

A scheduled transfer is the user's instruction to pay later or on repeat: rent on the 1st, savings every Friday, a supplier invoice on its due date. The interesting part of the backend is the date logic and making sure each due date pays exactly once.

This guide covers the data model, monthly dates, business days, idempotency toward the payment provider and the nightly job, with Go code using Encore.

The Scheduled Transfers Backend at a Glance

PieceWhat it doesBuilt with
Scheduled transfersThe standing instruction: amount, beneficiary, frequency, next due datePostgres
Transfer runsOne row per transfer and due date, with the amount at that timePostgres
Nightly jobOn business days, creates runs for everything due and advances datesCron
Submit workerSends each run to the payment provider with an idempotency keyPub/Sub
Bank holidaysNon-business days for your payment railPostgres

Why Is One Row Per Due Date the Core of the Design?

A recurring transfer is one instruction that produces many payments, and support, statements and disputes all ask about a specific payment: "did my rent go out on March 1?". Recording a run per transfer and due date, with a unique constraint on the pair, gives that answer a row, and it also makes the nightly job safe to rerun, since a second attempt to create the same run does nothing.

Copy the amount onto the run as well, because if the user changes the amount on the 2nd, the run from the 1st must still show what was sent.

How Do Monthly Dates Drift?

Most date libraries normalize overflow, and Go's time.AddDate documents that adding one month to October 31 yields December 1. A transfer created on January 31 that advances with AddDate(0, 1, 0) runs on March 3 instead of February 28, and every following month on the 3rd.

The fix is to store the anchor day (31) apart from the next due date and clamp it each month. February gets the 28th or 29th, March goes back to the 31st.

How Do Weekends and Bank Holidays Work?

Payment rails settle on business days, and their holidays differ: euro transfers under the SEPA Credit Transfer scheme follow the TARGET calendar, while US rails follow the Federal Reserve holiday schedule, where a holiday that falls on Sunday is observed on Monday.

The common rule for scheduled transfers is "following business day". The simplest implementation is to keep due dates nominal, skip the job on non-business days, and on the next business day pick up everything due on or before today. Saturday's rent and Monday's savings then both go out on Monday, and the run rows still show their nominal due dates.

The Data Model

-- transfers/migrations/1_create_transfers.up.sql CREATE TABLE scheduled_transfers ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, owner_id text NOT NULL, from_account text NOT NULL, beneficiary_id text NOT NULL, amount_minor bigint NOT NULL CHECK (amount_minor > 0), currency char(3) NOT NULL, frequency text NOT NULL CHECK (frequency IN ('once', 'weekly', 'monthly')), anchor_day smallint NOT NULL CHECK (anchor_day BETWEEN 1 AND 31), next_run_on date, status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'paused', 'cancelled', 'finished')), created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX scheduled_transfers_due ON scheduled_transfers (next_run_on) WHERE status = 'active'; CREATE TABLE transfer_runs ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, transfer_id bigint NOT NULL REFERENCES scheduled_transfers (id), due_on date NOT NULL, amount_minor bigint NOT NULL, status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'submitted', 'failed', 'skipped')), provider_ref text, created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (transfer_id, due_on) ); CREATE TABLE bank_holidays (day date PRIMARY KEY);

Amounts are integer minor units, as in storing money in Postgres, and the partial index keeps the nightly lookup on active transfers only.

Building It with Encore

Encore

Encore is a backend framework with built-in infrastructure: the database, the topic that feeds the submit worker, the cron job and the provider API key are declared in the Go code below. encore run starts Postgres and Pub/Sub locally, and deploying to AWS provisions RDS, SNS and SQS in your own account, with GCP getting Cloud SQL and Pub/Sub.

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

Run in your terminal to get started locally.

Creating and Cancelling Transfers

// transfers/transfers.go package transfers import ( "context" "time" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("transfers", sqldb.DatabaseConfig{ Migrations: "./migrations", }) type CreateParams struct { FromAccount string BeneficiaryID string AmountMinor int64 Currency string Frequency string // "once", "weekly" or "monthly" FirstRunOn string // YYYY-MM-DD } type Transfer struct { ID int64 NextRunOn string Status string } //encore:api auth method=POST path=/scheduled-transfers func Create(ctx context.Context, p *CreateParams) (*Transfer, error) { first, err := time.Parse(time.DateOnly, p.FirstRunOn) if err != nil { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "firstRunOn must be YYYY-MM-DD"} } today := time.Now().UTC().Truncate(24 * time.Hour) switch { case first.Before(today): return nil, &errs.Error{Code: errs.InvalidArgument, Message: "firstRunOn is in the past"} case p.AmountMinor <= 0: return nil, &errs.Error{Code: errs.InvalidArgument, Message: "amount must be positive"} case p.Frequency != "once" && p.Frequency != "weekly" && p.Frequency != "monthly": return nil, &errs.Error{Code: errs.InvalidArgument, Message: "unknown frequency"} } uid, _ := auth.UserID() // Check with your accounts service that uid owns FromAccount and BeneficiaryID // before storing them, since the payment provider may not check it for you. t := &Transfer{NextRunOn: p.FirstRunOn, Status: "active"} err = db.QueryRow(ctx, ` INSERT INTO scheduled_transfers (owner_id, from_account, beneficiary_id, amount_minor, currency, frequency, anchor_day, next_run_on) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id`, string(uid), p.FromAccount, p.BeneficiaryID, p.AmountMinor, p.Currency, p.Frequency, first.Day(), first, ).Scan(&t.ID) return t, err } //encore:api auth method=POST path=/scheduled-transfers/:id/cancel func Cancel(ctx context.Context, id int64) error { uid, _ := auth.UserID() res, err := db.Exec(ctx, ` UPDATE scheduled_transfers SET status = 'cancelled' WHERE id = $1 AND owner_id = $2 AND status IN ('active', 'paused')`, id, string(uid)) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.NotFound, Message: "no active transfer with that id"} } return nil }

Cancelling only flips the status, so a run already created for today stays pending, and the worker below skips it because it checks the transfer status under a row lock before paying, so a cancellation at 05:01 still wins over a payment that has not been sent.

Dates and the Nightly Job

// transfers/schedule.go package transfers import ( "context" "time" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/rlog" ) // nextRunOn returns the due date after prev. Monthly transfers keep their // anchor day and clamp it to the end of shorter months, so a transfer on the // 31st runs on Feb 28 and on Mar 31 again. func nextRunOn(freq string, anchorDay int, prev time.Time) (time.Time, bool) { switch freq { case "weekly": return prev.AddDate(0, 0, 7), true case "monthly": y, m, _ := prev.Date() first := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC) lastDay := first.AddDate(0, 1, -1).Day() return time.Date(first.Year(), first.Month(), min(anchorDay, lastDay), 0, 0, 0, 0, time.UTC), true default: return time.Time{}, false } } type TransferDue struct { RunID int64 } var TransfersDue = pubsub.NewTopic[*TransferDue]("transfers-due", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) var _ = cron.NewJob("enqueue-due-transfers", cron.JobConfig{ Title: "Create runs for scheduled transfers that are due", Schedule: "0 5 * * *", Endpoint: EnqueueDue, }) //encore:api private func EnqueueDue(ctx context.Context) error { today := time.Now().UTC().Truncate(24 * time.Hour) var holiday bool if err := db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM bank_holidays WHERE day = $1)`, today, ).Scan(&holiday); err != nil { return err } if holiday || today.Weekday() == time.Saturday || today.Weekday() == time.Sunday { rlog.Info("not a business day, transfers wait", "date", today.Format(time.DateOnly)) return nil } for { n, err := enqueueBatch(ctx, today) if err != nil { return err } if n == 0 { break } } return publishPending(ctx) } type dueTransfer struct { id, amount int64 freq string anchor int runOn time.Time } func enqueueBatch(ctx context.Context, today time.Time) (int, error) { tx, err := db.Begin(ctx) if err != nil { return 0, err } defer tx.Rollback() rows, err := tx.Query(ctx, ` SELECT id, amount_minor, frequency, anchor_day, next_run_on FROM scheduled_transfers WHERE status = 'active' AND next_run_on <= $1 ORDER BY next_run_on LIMIT 200 FOR UPDATE SKIP LOCKED`, today) if err != nil { return 0, err } var due []dueTransfer for rows.Next() { var d dueTransfer if err := rows.Scan(&d.id, &d.amount, &d.freq, &d.anchor, &d.runOn); err != nil { rows.Close() return 0, err } due = append(due, d) } rows.Close() if err := rows.Err(); err != nil { return 0, err } for _, d := range due { if _, err := tx.Exec(ctx, ` INSERT INTO transfer_runs (transfer_id, due_on, amount_minor) VALUES ($1, $2, $3) ON CONFLICT (transfer_id, due_on) DO NOTHING`, d.id, d.runOn, d.amount); err != nil { return 0, err } if next, ok := nextRunOn(d.freq, d.anchor, d.runOn); ok { _, err = tx.Exec(ctx, `UPDATE scheduled_transfers SET next_run_on = $2 WHERE id = $1`, d.id, next) } else { _, err = tx.Exec(ctx, `UPDATE scheduled_transfers SET next_run_on = NULL, status = 'finished' WHERE id = $1`, d.id) } if err != nil { return 0, err } } return len(due), tx.Commit() } // publishPending publishes every run that has not been submitted, including // runs left pending by an earlier failure. The worker ignores runs that are // no longer pending, so publishing one twice is harmless. func publishPending(ctx context.Context) error { rows, err := db.Query(ctx, `SELECT id FROM transfer_runs WHERE status = 'pending' ORDER BY id`) if err != nil { return err } defer rows.Close() for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return err } if _, err := TransfersDue.Publish(ctx, &TransferDue{RunID: id}); err != nil { return err } } return rows.Err() }

Creating runs and advancing dates happen in one transaction, so a crash leaves either both or neither. If the job did not run for three days, a weekly transfer's loop creates each missed due date as its own run, which matches what the user scheduled. Publishing happens after the commit and picks up every pending run, so a run whose publish failed yesterday gets another chance today.

Submitting Payments Exactly Once

// transfers/submit.go package transfers import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "time" "encore.dev/pubsub" ) var secrets struct { PaymentsAPIKey string } var errInsufficientFunds = errors.New("insufficient funds") var _ = pubsub.NewSubscription(TransfersDue, "submit-transfer", pubsub.SubscriptionConfig[*TransferDue]{ Handler: submitTransfer, RetryPolicy: &pubsub.RetryPolicy{MaxRetries: 5}, }) func submitTransfer(ctx context.Context, msg *TransferDue) error { var ( transferID, amount int64 dueOn time.Time runStatus, transferStatus, currency, from, beneficiary string ) // The row lock is held until the run is recorded, so a Cancel that arrives // during the provider call waits and then applies to later runs. tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() err = tx.QueryRow(ctx, ` SELECT r.transfer_id, r.due_on, r.amount_minor, r.status, t.status, t.currency, t.from_account, t.beneficiary_id FROM transfer_runs r JOIN scheduled_transfers t ON t.id = r.transfer_id WHERE r.id = $1 FOR UPDATE OF r, t`, msg.RunID, ).Scan(&transferID, &dueOn, &amount, &runStatus, &transferStatus, &currency, &from, &beneficiary) if err != nil { return err } if runStatus != "pending" { return nil // already handled by an earlier delivery } if transferStatus == "cancelled" || transferStatus == "paused" { if _, err := tx.Exec(ctx, `UPDATE transfer_runs SET status = 'skipped' WHERE id = $1 AND status = 'pending'`, msg.RunID); err != nil { return err } return tx.Commit() } // The same transfer and due date always produce the same key, so the // provider returns the original payment if this call is retried. key := fmt.Sprintf("scheduled-transfer-%d-%s", transferID, dueOn.Format(time.DateOnly)) ref, err := submitPayment(ctx, key, from, beneficiary, amount, currency) if errors.Is(err, errInsufficientFunds) { if _, err := tx.Exec(ctx, `UPDATE transfer_runs SET status = 'failed' WHERE id = $1 AND status = 'pending'`, msg.RunID); err != nil { return err } return tx.Commit() } if err != nil { return err // retried by Pub/Sub with backoff } if _, err := tx.Exec(ctx, ` UPDATE transfer_runs SET status = 'submitted', provider_ref = $2 WHERE id = $1 AND status = 'pending'`, msg.RunID, ref); err != nil { return err } return tx.Commit() } func submitPayment(ctx context.Context, idempotencyKey, from, beneficiary string, amount int64, currency string) (string, error) { body, err := json.Marshal(map[string]any{ "from_account": from, "beneficiary_id": beneficiary, "amount_minor": amount, "currency": currency, }) if err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://payments.example.com/v1/transfers", bytes.NewReader(body)) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+secrets.PaymentsAPIKey) req.Header.Set("Idempotency-Key", idempotencyKey) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() switch { case resp.StatusCode == http.StatusUnprocessableEntity: return "", errInsufficientFunds case resp.StatusCode >= 300: return "", fmt.Errorf("payments provider returned %d", resp.StatusCode) } var out struct { ID string `json:"id"` } if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return "", err } return out.ID, nil }

The idempotency key is what makes at-least-once delivery safe for money. Two deliveries of the same run can reach the provider, but with the same Idempotency-Key header, the convention the IETF Idempotency-Key draft describes, the second returns the first payment instead of creating another. The Pub/Sub docs cover delivery and retry policies, and the secrets docs cover setting PaymentsAPIKey per environment.

Running the Job

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 EnqueueDue from the dashboard or a test after inserting a few transfers, and a test for nextRunOn with January 31 is the cheapest guard against the drift bug. On AWS, Encore provisions an IAM role for the service, or a service account on GCP, and the database, topic and subscription are created in your account, as the AWS infrastructure docs describe.

Pave Bank built a bank in 9 months with Encore Platform, as its case study describes. When product asks for "every last business day of the month", a coding agent can add a frequency, extend nextRunOn and test it against the local database in one change, with no infrastructure to touch.

Best fit: banking and fintech teams who want standing orders with one auditable run per due date, running against their own AWS or GCP account.

Things to Decide Early

  • Account ownership. Check that from_account belongs to the user when creating a transfer, against the service that owns accounts.
  • Failed payments. Decide whether an insufficient-funds run retries later that day, the next business day, or not at all, and how the user is told.
  • Cut-off times. A payment rail has daily cut-offs, so the job's hour should leave time to submit before them.
  • Edits. Changing the amount or beneficiary affects future runs only, so keep past runs untouched and consider an audit table for edits.
  • Time zones. A due date is a calendar date in the bank's or user's zone; pick one and compute today in it.

Frequently asked questions

How do recurring payments work in a banking backend?

Each standing order stores its amount, beneficiary, frequency and next due date. A scheduled job finds orders that are due, records one run per order and due date, advances the next due date, and hands each run to the payment rail with an idempotency key so a retry never pays twice.

How do I handle a monthly transfer on the 31st?

Store the anchor day separately from the next due date and clamp it to the last day of shorter months, so the transfer runs on February 28 and returns to the 31st in March. Adding one month with a date library usually normalizes January 31 into early March instead.

What happens to a scheduled transfer due on a weekend or bank holiday?

Most banks execute it on the following business day, and a simple way to implement that is to run the job only on business days and pick up everything due on or before today, using a holiday table for your payment rail.

How do I schedule the nightly run with Encore?

Declare a cron job that calls a private endpoint, for example at 05:00 UTC every day. 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 endpoint directly or from a test.

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