Updated Nov 24, 20269 min read

Build a Bank Transaction Sync Backend for Open Banking Data

How to keep a copy of your users' bank transactions in sync with a cursor-based API: webhooks treated as hints, a paginated sync loop that restarts correctly, pending-to-posted updates, removals, a daily backstop and an idempotent write path on Postgres.

Illustration for Build a Bank Transaction Sync Backend for Open Banking Data

A fintech app that shows spending or underwrites from bank data needs its own copy of each user's transactions, kept current as the bank posts, edits and deletes them.

Aggregators such as Plaid expose this as a cursor-based sync API, which looks simple until pagination fails halfway or a pending charge posts with a new ID. This guide builds the sync service on Postgres, from the webhook to an idempotent write path.

What does a transaction sync have to handle?

Plaid's /transactions/sync endpoint takes the cursor you stored after the last sync and returns added, modified and removed arrays, a next_cursor and has_more, with up to 500 updates per page. Plaid checks institutions for new data one to four times a day and sends a SYNC_UPDATES_AVAILABLE webhook when something changed.

CaseWhat arrivesWhat the backend does
New transactionIn addedInsert by transaction_id
Edited transactionIn modifiedUpdate the stored row
Pending charge postsPending ID in removed, posted version in addedDelete and insert in the same database transaction
Failure mid-paginationError such as TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATIONRestart from the cursor the loop started with
Missed webhookNothingA daily sync for every item catches up

Amounts follow Plaid's sign convention, where positive values are money leaving the account and negative values money coming in, so a refund is negative. Store them as NUMERIC rather than a float, since the ledger and statement code that reads them should not inherit rounding errors.

How should the webhook be handled?

The webhook body carries only the item_id and flags such as initial_update_complete, never transaction data, so treat it as a hint to sync that item. The handler checks that the item exists, queues a sync and returns 200 quickly, and the sync itself calls Plaid with your credentials, which means a forged webhook can at most trigger an extra sync of a known item. Still verify the Plaid-Verification header as described in Plaid's webhook verification guide before going live, and see webhook signature verification for the general pattern.

How does the sync loop stay correct?

The loop collects every page into memory before writing anything, because applying page one and then failing on page three would leave a cursor that skips updates. When Plaid returns the mutation error, the loop throws away what it collected and starts again from the original cursor, as the docs require.

Two deliveries for the same item can run at once, for example a webhook and the daily backstop. The write transaction locks the item row and compares the stored cursor with the one the loop started from, and if another sync already moved it, this run stops before any write, so the same update is never applied twice.

How does Encore run the sync service?

Encore is a backend framework with built-in infrastructure, so the webhook, the queue of sync requests, the database and the daily backstop are declared in one service and deployed to your own AWS or GCP account. Per the AWS infrastructure docs, that is RDS for the transactions and SNS with SQS for the queue, which keeps bank data inside an account you control.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The webhook queues work, the subscriber runs the paginated sync, and the cron job requests a sync for every item once a day:

// banksync/banksync.go package banksync import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "time" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) // Set with `encore secret set --type prod PlaidSecret`; values never live in the repo. var secrets struct { PlaidClientID string PlaidSecret string } // Use https://sandbox.plaid.com while testing. const plaidBaseURL = "https://production.plaid.com" var db = sqldb.NewDatabase("banksync", sqldb.DatabaseConfig{Migrations: "./migrations"}) var httpClient = &http.Client{Timeout: 30 * time.Second} type SyncRequested struct { ItemID string } var SyncRequests = pubsub.NewTopic[*SyncRequested]("bank-sync-requested", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type webhook struct { WebhookType string `json:"webhook_type"` WebhookCode string `json:"webhook_code"` ItemID string `json:"item_id"` } // The webhook is only a hint: it names an item, and the sync fetches the data itself. // //encore:api public raw method=POST path=/plaid/webhook func PlaidWebhook(w http.ResponseWriter, req *http.Request) { // In production, verify the Plaid-Verification header first, a JWT signed with // Plaid's webhook key, and reject requests without a valid one. var hook webhook if err := json.NewDecoder(io.LimitReader(req.Body, 1<<20)).Decode(&hook); err != nil { http.Error(w, "bad payload", http.StatusBadRequest) return } if hook.WebhookType == "TRANSACTIONS" && hook.WebhookCode == "SYNC_UPDATES_AVAILABLE" { var known bool err := db.QueryRow(req.Context(), `SELECT EXISTS (SELECT 1 FROM plaid_items WHERE item_id = $1)`, hook.ItemID).Scan(&known) if err != nil { http.Error(w, "lookup failed", http.StatusInternalServerError) return } if known { if _, err := SyncRequests.Publish(req.Context(), &SyncRequested{ItemID: hook.ItemID}); err != nil { http.Error(w, "queue failed", http.StatusInternalServerError) return } } } w.WriteHeader(http.StatusOK) } type plaidTxn struct { TransactionID string `json:"transaction_id"` AccountID string `json:"account_id"` Amount json.Number `json:"amount"` Currency *string `json:"iso_currency_code"` Date string `json:"date"` Name string `json:"name"` Pending bool `json:"pending"` } type syncPage struct { Added []plaidTxn `json:"added"` Modified []plaidTxn `json:"modified"` Removed []struct { TransactionID string `json:"transaction_id"` } `json:"removed"` NextCursor string `json:"next_cursor"` HasMore bool `json:"has_more"` } var errMutation = errors.New("transactions changed during pagination") func fetchPage(ctx context.Context, accessToken, cursor string) (*syncPage, error) { body := map[string]any{ "client_id": secrets.PlaidClientID, "secret": secrets.PlaidSecret, "access_token": accessToken, "count": 500, } if cursor != "" { body["cursor"] = cursor } buf, err := json.Marshal(body) if err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, plaidBaseURL+"/transactions/sync", bytes.NewReader(buf)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") resp, err := httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { var pe struct { ErrorCode string `json:"error_code"` } _ = json.NewDecoder(resp.Body).Decode(&pe) if pe.ErrorCode == "TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION" { return nil, errMutation } return nil, fmt.Errorf("transactions/sync: status %d, %s", resp.StatusCode, pe.ErrorCode) } dec := json.NewDecoder(resp.Body) dec.UseNumber() var page syncPage if err := dec.Decode(&page); err != nil { return nil, err } return &page, nil } var _ = pubsub.NewSubscription(SyncRequests, "sync-item", pubsub.SubscriptionConfig[*SyncRequested]{ Handler: syncItem, RetryPolicy: &pubsub.RetryPolicy{ MinBackoff: 30 * time.Second, MaxBackoff: 10 * time.Minute, MaxRetries: 8, }, }) func syncItem(ctx context.Context, e *SyncRequested) error { var accessToken, start string err := db.QueryRow(ctx, `SELECT access_token, sync_cursor FROM plaid_items WHERE item_id = $1`, e.ItemID).Scan(&accessToken, &start) if errors.Is(err, sqldb.ErrNoRows) { return nil } else if err != nil { return err } // Collect every page before writing, restarting from the original cursor on a mutation error. var changed []plaidTxn var removed []string cursor, restarts := start, 0 for { page, err := fetchPage(ctx, accessToken, cursor) if errors.Is(err, errMutation) && restarts < 3 { restarts++ cursor, changed, removed = start, nil, nil continue } if err != nil { return err } changed = append(changed, page.Added...) changed = append(changed, page.Modified...) for _, r := range page.Removed { removed = append(removed, r.TransactionID) } cursor = page.NextCursor if !page.HasMore { break } } tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var current string if err := tx.QueryRow(ctx, `SELECT sync_cursor FROM plaid_items WHERE item_id = $1 FOR UPDATE`, e.ItemID).Scan(&current); err != nil { return err } if current != start { return nil // another delivery already applied this update } for _, id := range removed { if _, err := tx.Exec(ctx, `DELETE FROM bank_transactions WHERE transaction_id = $1`, id); err != nil { return err } } for _, t := range changed { _, err := tx.Exec(ctx, ` INSERT INTO bank_transactions (transaction_id, item_id, account_id, amount, currency, posted_on, name, pending) VALUES ($1, $2, $3, $4::numeric, $5, $6::date, $7, $8) ON CONFLICT (transaction_id) DO UPDATE SET amount = EXCLUDED.amount, currency = EXCLUDED.currency, posted_on = EXCLUDED.posted_on, name = EXCLUDED.name, pending = EXCLUDED.pending, updated_at = now()`, t.TransactionID, e.ItemID, t.AccountID, t.Amount.String(), t.Currency, t.Date, t.Name, t.Pending) if err != nil { return err } } if _, err := tx.Exec(ctx, `UPDATE plaid_items SET sync_cursor = $2, synced_at = now() WHERE item_id = $1`, e.ItemID, cursor); err != nil { return err } return tx.Commit() } // Backstop for missed webhooks; runs on deployed environments, not under `encore run`. var _ = cron.NewJob("bank-sync-backstop", cron.JobConfig{ Title: "Request a sync for every bank item", Schedule: "0 5 * * *", Endpoint: SyncAll, }) //encore:api private method=POST path=/internal/bank-sync-all func SyncAll(ctx context.Context) error { rows, err := db.Query(ctx, `SELECT item_id FROM plaid_items`) if err != nil { return err } defer rows.Close() for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return err } if _, err := SyncRequests.Publish(ctx, &SyncRequested{ItemID: id}); err != nil { return err } } return rows.Err() }
-- banksync/migrations/1_create_tables.up.sql CREATE TABLE plaid_items ( item_id TEXT PRIMARY KEY, access_token TEXT NOT NULL, sync_cursor TEXT NOT NULL DEFAULT '', synced_at TIMESTAMPTZ ); CREATE TABLE bank_transactions ( transaction_id TEXT PRIMARY KEY, item_id TEXT NOT NULL REFERENCES plaid_items (item_id), account_id TEXT NOT NULL, amount NUMERIC(19, 4) NOT NULL, currency TEXT, posted_on DATE NOT NULL, name TEXT NOT NULL, pending BOOLEAN NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX bank_transactions_account_idx ON bank_transactions (account_id, posted_on DESC);

The Plaid keys are Encore secrets, set per environment with encore secret set and kept out of the repository, so an AI agent working in the code cannot read or leak the production values. The access tokens in plaid_items are credentials too, so restrict who can query that table.

A sync that keeps failing is retried with backoff and then moved to a dead-letter queue, per the Pub/Sub docs, where it can be inspected and released once the cause is fixed. encore run starts Postgres and the topic locally, so the webhook and the sync loop can be tested against Plaid's sandbox, while the backstop cron job only runs on deployed environments, as the cron jobs docs describe, and is tested by calling POST /internal/bank-sync-all directly.

To deploy, connect your AWS or GCP account as described in Connect your cloud account and push.

When a coding agent is asked to store a new field such as the merchant name, it changes the struct, the upsert and a migration in one diff, and runs the sync against the sandbox locally before anyone reviews it.

Best fit: Fintech teams that want bank transaction data synced into Postgres in their own cloud account, with the sync logic, queue and schedule in one reviewed codebase.

What should you test before go-live?

Link a sandbox item, sync it twice and confirm the second sync writes nothing new. Create a pending transaction with Plaid's sandbox tools, let it post and check that the pending row disappears as the posted row appears in the same sync, then deliver the same sync request twice concurrently and confirm the cursor moves once and no transaction is duplicated.

Frequently asked questions

How does Plaid transactions sync work?

You call /transactions/sync with the cursor you stored last time, and it returns transactions added, modified and removed since that cursor, plus a next_cursor and a has_more flag. You keep calling until has_more is false, apply all the changes, and store the final cursor for the next sync.

What should happen when a sync fails halfway through pagination?

Restart the whole loop from the cursor you started with, not from the page that failed. Plaid's docs say that when a paginated update fails, for example with TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION, the entire pagination loop must be restarted from the first page's cursor.

Why do pending transactions disappear?

When a pending card transaction posts, the pending version is reported as removed and the posted version arrives as a new transaction with a different ID, linked through pending_transaction_id. A sync that applies removals and additions in the same database transaction keeps balances and lists consistent.

How do I run a bank transaction sync service in my own AWS account?

With Encore you declare the Postgres database, a Pub/Sub topic for sync requests and a cron job for the daily backstop in the service code, and store the API keys as Encore secrets. Deploying provisions RDS and SNS with SQS in your own AWS account, or Cloud SQL and Pub/Sub on GCP.

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