How to build the backend that produces monthly account statements for a fintech product: period cutoffs, balance snapshots from the ledger, idempotent generation per account, PDF storage, customer notification and the record retention questions regulators ask.

Monthly statements look like a reporting feature until the first month a customer disputes a number.
A statement records what the account did in a closed period, and it has to show the same balances in two years that it showed on the day it was sent, even as transactions keep arriving and ledgers get corrected.
This guide covers cutoffs, balances, generation, storage and delivery.
For US consumer accounts with electronic transfers, Regulation E section 1005.9(b) requires a periodic statement for each monthly cycle with a transfer, and at least quarterly otherwise. It lists the content: each transfer's amount, date, type and counterparty, the account number, fees, opening and closing balances, and an address and phone number for errors. Card, lending and non-US products have their own rules, so treat the regulation as the floor for the data model rather than a complete specification.
Each statement period needs an unambiguous boundary, so store period_start and period_end as timestamps in UTC computed from the account's statement timezone, and treat the end as exclusive. Transactions are assigned by their posting time, not their authorization time, so a card authorization on the 31st that posts on the 2nd belongs to the next statement. Decide this once and document it, since support staff will be asked about it every month.
Opening and closing balances must come from the ledger, not from a balance column that changes every second:
SELECT
coalesce(sum(amount_cents) FILTER (WHERE posted_at < $2), 0) AS opening_cents,
coalesce(sum(amount_cents) FILTER (WHERE posted_at < $3), 0) AS closing_cents
FROM ledger_entries
WHERE account_id = $1;
Regenerating a statement months later then produces identical numbers, and a correction to a closed period should be posted as a new entry in the current period, so closed statements never change.
Period close produces one statement per account at the same moment, which is a fan-out problem:
Storing PDFs in a private bucket with S3 versioning enabled means an accidental overwrite or delete of a sent statement can be undone, and retention needs the same care: Regulation E's record retention rule requires evidence of compliance for at least two years, and many products keep statements far longer. Keep the generated PDF, the template version and the ledger entry IDs it summarized, so any statement can be explained later.
Best fit: ledger-derived balances, per-account idempotent jobs and private storage with signed URLs.
Encore is a backend framework with built-in infrastructure, so the schedule, the fan-out queue, the bucket and the endpoints for a statement service are declared together in Go and provisioned in your own AWS or GCP account on deploy. Simon Vans-Colina, CTO at Pave Bank, put it this way on the customers page: "Using Encore is an unfair advantage."

Run in your terminal to get started locally.
package statements
import (
"context"
"fmt"
"time"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/storage/objects"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("statements", sqldb.DatabaseConfig{Migrations: "./migrations"})
var PDFs = objects.NewBucket("statement-pdfs", objects.BucketConfig{Versioned: true})
type GenerateStatement struct {
AccountID string `json:"account_id"`
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
}
var Generate = pubsub.NewTopic[*GenerateStatement]("generate-statement", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
var _ = cron.NewJob("monthly-statements", cron.JobConfig{
Title: "Fan out statement generation for the closed month",
Schedule: "0 6 1 * *", // 06:00 UTC on the 1st, after late postings settle
Endpoint: CloseMonth,
})
//encore:api private
func CloseMonth(ctx context.Context) error {
// Calendar months in UTC; per-timezone cutoffs would compute these per account.
now := time.Now().UTC()
end := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
start := end.AddDate(0, -1, 0)
rows, err := db.Query(ctx, `SELECT id FROM accounts WHERE opened_at < $1`, end)
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 := Generate.Publish(ctx, &GenerateStatement{AccountID: id, PeriodStart: start, PeriodEnd: end}); err != nil {
return err
}
}
return rows.Err()
}
var _ = pubsub.NewSubscription(Generate, "render-statement", pubsub.SubscriptionConfig[*GenerateStatement]{
Handler: render,
MaxConcurrency: 10,
})
func render(ctx context.Context, m *GenerateStatement) error {
var opening, closing int64
if err := db.QueryRow(ctx, `
SELECT coalesce(sum(amount_cents) FILTER (WHERE posted_at < $2), 0),
coalesce(sum(amount_cents) FILTER (WHERE posted_at < $3), 0)
FROM ledger_entries WHERE account_id = $1`,
m.AccountID, m.PeriodStart, m.PeriodEnd).Scan(&opening, &closing); err != nil {
return err
}
pdf, err := renderPDF(ctx, m, opening, closing)
if err != nil {
return err
}
key := fmt.Sprintf("%s/%s.pdf", m.AccountID, m.PeriodStart.Format("2006-01"))
w := PDFs.Upload(ctx, key, objects.WithUploadAttrs(objects.UploadAttrs{ContentType: "application/pdf"}))
if _, err := w.Write(pdf); err != nil {
w.Abort(err)
return err
}
if err := w.Close(); err != nil {
return err
}
// The unique key on (account_id, period_start) makes redelivery a no-op.
_, err = db.Exec(ctx, `
INSERT INTO statements (account_id, period_start, period_end, opening_cents, closing_cents, object_key)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (account_id, period_start) DO NOTHING`,
m.AccountID, m.PeriodStart, m.PeriodEnd, opening, closing, key)
return err
}
type DownloadResponse struct {
URL string `json:"url"`
}
//encore:api auth method=GET path=/accounts/:accountID/statements/:period
func Download(ctx context.Context, accountID, period string) (*DownloadResponse, error) {
// Check here that the authenticated user owns accountID.
u, err := PDFs.SignedDownloadURL(ctx, accountID+"/"+period+".pdf", objects.WithTTL(10*time.Minute))
if err != nil {
return nil, err
}
return &DownloadResponse{URL: u.URL}, nil
}
func renderPDF(ctx context.Context, m *GenerateStatement, opening, closing int64) ([]byte, error) {
// Render the statement template to PDF here and record the template version.
return []byte{}, nil
}
The cron job is managed by the Encore platform in deployed environments and does not run locally, so during development encore run starts Postgres, the topic and local object storage, and you call CloseMonth by hand to generate a month of statements. The Pub/Sub docs cover retries and dead-letter queues for accounts whose rendering fails, and the object storage docs cover signed URLs. On AWS the bucket is S3 and the topic runs on SNS and SQS, with Encore provisioning an IAM role for the service.
An AI coding agent asked to add a field to statements can change the query, the template input and the migration in one diff, and run the whole close locally against seeded ledger data before review.
Best fit: fintech teams on AWS or GCP producing statements from a ledger who want the job, queue and storage defined with the code.
Define the period boundaries and posting rules first, compute balances from ledger entries, and make generation idempotent per account and period. Fan out with a queue so one bad account does not block the rest, store PDFs privately with versioning, and keep enough metadata to explain any statement years later.
For US consumer accounts that support electronic fund transfers, Regulation E requires a periodic statement for each monthly cycle in which a transfer occurred and at least quarterly otherwise. Other account types and jurisdictions have their own rules, so confirm the requirement with counsel for each product.
Give each statement a natural key of account ID and period, enforce it with a unique constraint, and derive the storage key from the same pair. A retried job then overwrites nothing and inserts nothing new, and a crashed run can be restarted.
From the ledger. Compute the opening balance as the sum of entries before the period start and the closing balance as the sum before the period end, so a statement can be regenerated later with exactly the same numbers even after new transactions arrive.
Declare a cron job with a monthly schedule that publishes one Pub/Sub message per account, a subscriber that renders the PDF and uploads it to an Encore bucket, and an endpoint that returns a short-lived signed download URL. The bucket and topic are provisioned in your own AWS or GCP account.
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.