Nov 19, 202613 min read

Invoicing Backend: Invoice Numbers, PDFs, Reminders and Payments

How to build the backend behind invoicing: gapless invoice numbers assigned at issue time, frozen line items, PDFs rendered once and stored privately, payments recorded exactly once from webhooks, and overdue reminders that never send twice.

Illustration for Invoicing Backend: Invoice Numbers, PDFs, Reminders and Payments

An invoice looks like a table of line items and a total, but the backend around it carries legal and financial weight. The number has to be unique and in sequence, the amounts cannot change after the customer has seen them, and a payment that arrives twice must still count once.

This guide builds that backend in Go with Postgres: draft invoices, numbering at issue time, PDFs rendered once into private storage, payments recorded from provider webhooks and a daily job that queues overdue reminders.

Invoicing backend at a glance

JobApproachWhat breaks if you skip it
Invoice numbersCounter row per tenant and year, taken at issue timeGaps or duplicates in the series
AmountsInteger cents, tax per line, totals computed onceRounding drift between PDF and ledger
ImmutabilityStatus check plus a trigger on line itemsEdits to an invoice the customer already has
PDFRendered by a subscriber, stored in a private bucketSlow issue requests, public invoice links
PaymentsUnique provider event ID, ON CONFLICT DO NOTHINGDouble-counted payments
RemindersUnique row per invoice and reminder kindCustomers emailed twice

Why do invoice numbers go wrong?

The usual approach is SELECT max(number) + 1, which hands two concurrent requests the same number, or a Postgres sequence, which never rolls back and so leaves gaps every time an issuing transaction fails. A number assigned when the draft is created has the same problem, since drafts get abandoned.

The EU VAT Directive lists "a sequential number, based on one or more series, which uniquely identifies the invoice" among the details an invoice must contain, and other jurisdictions have comparable expectations. A counter row updated with an upsert inside the issuing transaction gives both properties: the row lock serializes issuers for that tenant, and a rollback undoes the increment. The cost is that invoices for one tenant are numbered one at a time, which is far above the rate any single tenant issues invoices.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and the invoicing service declares its Postgres database, a Pub/Sub topic for issued invoices, a private bucket for PDFs and a cron job for reminders, and the rest of the app calls it as a typed service API.

Application code passes through Encore and infrastructure guardrails to resources provisioned 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 billing --example=hello-world$ cd billing && mkdir -p invoices/migrations$ go get github.com/go-pdf/fpdf

Schema: numbers, lines and frozen invoices

The migration puts the rules into the database: number stays NULL until issue, UNIQUE (tenant_id, number) rejects duplicates, and a trigger refuses any change to line items once the invoice has left draft:

-- invoices/migrations/1_create_invoices.up.sql CREATE TABLE invoice_counters ( tenant_id TEXT NOT NULL, series TEXT NOT NULL, -- for example the year: "2026" last INT NOT NULL DEFAULT 0, PRIMARY KEY (tenant_id, series) ); CREATE TABLE invoices ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id TEXT NOT NULL, customer_id TEXT NOT NULL, number TEXT, -- NULL while the invoice is a draft status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'open', 'paid', 'void')), currency CHAR(3) NOT NULL, total_cents BIGINT NOT NULL DEFAULT 0, issued_at TIMESTAMPTZ, due_at TIMESTAMPTZ, paid_at TIMESTAMPTZ, pdf_key TEXT, UNIQUE (tenant_id, number) ); CREATE TABLE invoice_lines ( id BIGSERIAL PRIMARY KEY, invoice_id UUID NOT NULL REFERENCES invoices(id), description TEXT NOT NULL, quantity INT NOT NULL CHECK (quantity > 0), unit_cents BIGINT NOT NULL, tax_basis_points INT NOT NULL DEFAULT 0 -- 2000 = 20% ); -- Lines are frozen once the invoice leaves draft. -- Check both OLD and NEW invoice_id so a line cannot be moved off a finalized invoice. CREATE FUNCTION lines_only_while_draft() RETURNS trigger AS $$ BEGIN IF TG_OP = 'INSERT' THEN IF EXISTS (SELECT 1 FROM invoices WHERE id = NEW.invoice_id AND status <> 'draft') THEN RAISE EXCEPTION 'invoice is finalized'; END IF; ELSIF TG_OP = 'UPDATE' THEN IF EXISTS (SELECT 1 FROM invoices WHERE id IN (NEW.invoice_id, OLD.invoice_id) AND status <> 'draft') THEN RAISE EXCEPTION 'invoice is finalized'; END IF; ELSIF TG_OP = 'DELETE' THEN IF EXISTS (SELECT 1 FROM invoices WHERE id = OLD.invoice_id AND status <> 'draft') THEN RAISE EXCEPTION 'invoice is finalized'; END IF; END IF; RETURN COALESCE(NEW, OLD); END $$ LANGUAGE plpgsql; CREATE TRIGGER lines_frozen BEFORE INSERT OR UPDATE OR DELETE ON invoice_lines FOR EACH ROW EXECUTE FUNCTION lines_only_while_draft(); CREATE TABLE payments ( id BIGSERIAL PRIMARY KEY, invoice_id UUID NOT NULL REFERENCES invoices(id), provider_event_id TEXT NOT NULL UNIQUE, -- the webhook event ID amount_cents BIGINT NOT NULL CHECK (amount_cents > 0), received_at TIMESTAMPTZ NOT NULL DEFAULT now() );

Issue an invoice

Issue locks the draft, takes the next number from the counter and computes the total from the lines in one statement, so the PDF, the ledger and the customer all see the same amount:

// invoices/invoices.go package invoices import ( "context" "fmt" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("invoices", sqldb.DatabaseConfig{Migrations: "./migrations"}) // Rendering, email and reporting subscribe to this. var InvoiceIssued = pubsub.NewTopic[*IssuedEvent]("invoice-issued", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type IssuedEvent struct { InvoiceID string `json:"invoice_id"` Number string `json:"number"` } type IssueResponse struct { Number string `json:"number"` TotalCents int64 `json:"total_cents"` } // Issue moves a draft to open and gives it the next number in the // tenant's series. The counter update and the status change share one // transaction, so a failure rolls back both and no number is skipped. // //encore:api private method=POST path=/invoices/:id/issue func Issue(ctx context.Context, id string) (*IssueResponse, error) { tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() var tenant string err = tx.QueryRow(ctx, ` SELECT tenant_id FROM invoices WHERE id = $1 AND status = 'draft' FOR UPDATE`, id).Scan(&tenant) if err != nil { return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "invoice is not a draft"} } // The upsert locks the counter row until commit, so two invoices for the // same tenant are numbered one after the other. var series string var n int err = tx.QueryRow(ctx, ` INSERT INTO invoice_counters (tenant_id, series, last) VALUES ($1, to_char(now(), 'YYYY'), 1) ON CONFLICT (tenant_id, series) DO UPDATE SET last = invoice_counters.last + 1 RETURNING series, last`, tenant).Scan(&series, &n) if err != nil { return nil, err } number := fmt.Sprintf("%s-%05d", series, n) var total int64 err = tx.QueryRow(ctx, ` UPDATE invoices i SET status = 'open', number = $2, issued_at = now(), due_at = now() + interval '30 days', total_cents = (SELECT COALESCE(SUM(quantity * unit_cents + ROUND(quantity * unit_cents * tax_basis_points / 10000.0)), 0) FROM invoice_lines WHERE invoice_id = i.id) WHERE id = $1 RETURNING total_cents`, id, number).Scan(&total) if err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, err } _, _ = InvoiceIssued.Publish(ctx, &IssuedEvent{InvoiceID: id, Number: number}) return &IssueResponse{Number: number, TotalCents: total}, nil }

If any step fails, the deferred rollback undoes the counter increment too, so no number is lost. If two issuers run at once for the same tenant, the lock on the counter row means one gets 2026-00001 and the other 2026-00002, one after the other, as the second waits for the counter row. Totals use integer cents, with tax rounded per line from basis points.

Render the PDF once

A subscription renders the PDF after the issue transaction commits, so a slow renderer never holds the counter lock. The handler can run more than once, and the object key comes from the invoice ID, so a redelivery overwrites the same file. Customers get a short-lived signed link, never a public URL:

// invoices/pdf.go package invoices import ( "bytes" "context" "fmt" "time" "encore.dev/pubsub" "encore.dev/storage/objects" "github.com/go-pdf/fpdf" ) var PDFs = objects.NewBucket("invoice-pdfs", objects.BucketConfig{}) var _ = pubsub.NewSubscription(InvoiceIssued, "render-pdf", pubsub.SubscriptionConfig[*IssuedEvent]{ Handler: func(ctx context.Context, e *IssuedEvent) error { // Safe to run twice: the key is derived from the invoice and the // upload overwrites the same object. key := fmt.Sprintf("%s.pdf", e.InvoiceID) pdf, err := render(ctx, e.InvoiceID, e.Number) if err != nil { return err } w := PDFs.Upload(ctx, key) if _, err := w.Write(pdf); err != nil { w.Abort(err) return err } if err := w.Close(); err != nil { return err } _, err = db.Exec(ctx, `UPDATE invoices SET pdf_key = $2 WHERE id = $1`, e.InvoiceID, key) return err }, }) func render(ctx context.Context, id, number string) ([]byte, error) { rows, err := db.Query(ctx, ` SELECT description, quantity, unit_cents FROM invoice_lines WHERE invoice_id = $1 ORDER BY id`, id) if err != nil { return nil, err } defer rows.Close() p := fpdf.New("P", "mm", "A4", "") p.AddPage() p.SetFont("Helvetica", "B", 16) p.Cell(0, 10, "Invoice "+number) p.Ln(14) p.SetFont("Helvetica", "", 11) for rows.Next() { var desc string var qty int var unit int64 if err := rows.Scan(&desc, &qty, &unit); err != nil { return nil, err } p.CellFormat(120, 8, desc, "", 0, "L", false, 0, "") p.CellFormat(20, 8, fmt.Sprint(qty), "", 0, "R", false, 0, "") p.CellFormat(30, 8, fmt.Sprintf("%.2f", float64(unit)/100), "", 1, "R", false, 0, "") } if err := rows.Err(); err != nil { return nil, err } var buf bytes.Buffer if err := p.Output(&buf); err != nil { return nil, err } return buf.Bytes(), nil } type LinkResponse struct { URL string `json:"url"` } //encore:api private method=GET path=/invoices/:id/pdf func PDFLink(ctx context.Context, id string) (*LinkResponse, error) { u, err := PDFs.SignedDownloadURL(ctx, id+".pdf", objects.WithTTL(10*time.Minute)) if err != nil { return nil, err } return &LinkResponse{URL: u.URL}, nil }

The renderer here uses fpdf and prints only the lines; a production template adds the seller and buyer details, tax breakdown and payment terms that your jurisdiction requires.

Record payments and queue reminders

The webhook receiver verifies the provider's signature, as in the Stripe webhooks guide and webhook signature verification, then calls RecordPayment. The unique event ID makes redelivery harmless, and the invoice flips to paid only when payments cover the total:

-- invoices/migrations/2_create_reminders.up.sql CREATE TABLE reminders ( invoice_id UUID NOT NULL REFERENCES invoices(id), kind TEXT NOT NULL, -- 'due-soon', 'overdue-7', ... sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (invoice_id, kind) );
// invoices/payments.go package invoices import ( "context" "encore.dev/beta/errs" "encore.dev/cron" "encore.dev/pubsub" ) type PaymentParams struct { InvoiceID string `json:"invoice_id"` ProviderEventID string `json:"provider_event_id"` AmountCents int64 `json:"amount_cents"` } // RecordPayment is called by the webhook receiver after it verifies the // provider's signature. Providers redeliver events, so the event ID is a // unique key and a repeat delivery changes nothing. // //encore:api private method=POST path=/invoices/payments func RecordPayment(ctx context.Context, p *PaymentParams) error { if p.AmountCents <= 0 { return &errs.Error{Code: errs.InvalidArgument, Message: "amount must be positive"} } tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() // A redelivery of an already-recorded event succeeds even if the invoice is now paid. var already bool err = tx.QueryRow(ctx, ` SELECT EXISTS(SELECT 1 FROM payments WHERE provider_event_id = $1)`, p.ProviderEventID).Scan(&already) if err != nil { return err } if already { return nil } // Lock the invoice and require it to be open before recording a new payment. var status string err = tx.QueryRow(ctx, ` SELECT status FROM invoices WHERE id = $1 FOR UPDATE`, p.InvoiceID).Scan(&status) if err != nil { return err } if status != "open" { return &errs.Error{Code: errs.FailedPrecondition, Message: "invoice is not open"} } res, err := tx.Exec(ctx, ` INSERT INTO payments (invoice_id, provider_event_id, amount_cents) VALUES ($1, $2, $3) ON CONFLICT (provider_event_id) DO NOTHING`, p.InvoiceID, p.ProviderEventID, p.AmountCents) if err != nil { return err } if res.RowsAffected() == 0 { return nil // already recorded } _, err = tx.Exec(ctx, ` UPDATE invoices i SET status = 'paid', paid_at = now() WHERE i.id = $1 AND i.status = 'open' AND (SELECT SUM(amount_cents) FROM payments WHERE invoice_id = i.id) >= i.total_cents`, p.InvoiceID) if err != nil { return err } return tx.Commit() } type Reminder struct { InvoiceID string `json:"invoice_id"` Kind string `json:"kind"` } var Reminders = pubsub.NewTopic[*Reminder]("invoice-reminders", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) var _ = cron.NewJob("invoice-reminders", cron.JobConfig{ Title: "Queue overdue invoice reminders", Schedule: "0 8 * * *", Endpoint: QueueReminders, }) // QueueReminders claims a reminder row per invoice and kind before it // publishes, so running the job twice in a day sends nothing twice. If the // publish fails, the claim is removed so the next run retries it. // //encore:api private func QueueReminders(ctx context.Context) error { rows, err := db.Query(ctx, ` SELECT id FROM invoices WHERE status = 'open' AND due_at < now() - interval '7 days'`) if err != nil { return err } var ids []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { rows.Close() return err } ids = append(ids, id) } rows.Close() if err := rows.Err(); err != nil { return err } for _, id := range ids { res, err := db.Exec(ctx, ` INSERT INTO reminders (invoice_id, kind) VALUES ($1, 'overdue-7') ON CONFLICT DO NOTHING`, id) if err != nil { return err } if res.RowsAffected() == 0 { continue // already queued } if _, err := Reminders.Publish(ctx, &Reminder{InvoiceID: id, Kind: "overdue-7"}); err != nil { _, _ = db.Exec(ctx, `DELETE FROM reminders WHERE invoice_id = $1 AND kind = 'overdue-7'`, id) return err } } return nil }

encore run starts Postgres locally and applies both migrations. The cron job is Encore platform Managed: it does not run under encore run or in preview environments, and because QueueReminders is a plain function, a Go test can call it directly. The reminder row is claimed before publishing, so a second run on the same day queues nothing, and a failed publish removes the claim so the next run retries it. For events that must never be lost between the commit and the publish, the outbox package writes them in the same transaction.

On deploy, Encore creates the database, topic and bucket in your own AWS or GCP account and provisions an IAM role for the service, or a service account on GCP.

When finance asks for a new rule, such as a purchase order number on every invoice, a coding agent changes the migration, the Issue query and the PDF in one diff and tests it against the local database, with no separate infrastructure change.

Invoicing on plain Postgres

The schema, the counter upsert and the unique indexes are ordinary Postgres, so the same design runs on any setup. You then provision the database and bucket, run migrations in CI, wire a queue for the PDF job, schedule the reminder job and manage credentials for each environment yourself. Keep numbering and payment recording in one service either way, so no other code path can write an invoice number or a payment.

How do tax and numbering rules fit in?

The code above keeps one numbering series per tenant and year. Some countries require separate series for credit notes, or a prefix per business unit, and the counter table supports that by adding the series name as a key. Whether a given invoice must carry a VAT number, a tax breakdown by rate or particular wording depends on the seller and buyer countries, so treat the PDF template as something an accountant signs off on, and store the tax rate on each line so past invoices stay reproducible when rates change.

How to choose

Use Encore if you want the invoice service, its database, bucket, event topic and reminder job declared together and running locally and in your own cloud account from the first commit. Build on plain Postgres and your existing queue and scheduler if those are in place and the team already owns migrations and infrastructure per environment. Use a hosted billing product instead when you need tax calculation, dunning and payment collection from one vendor and your invoices follow its format.

Frequently asked questions

Can invoice numbers have gaps?

No. EU VAT rules list a sequential number, based on one or more series, among the details an invoice must carry, and many other tax authorities expect the same, so a missing number invites questions. Assign the number only when the invoice is issued, in the same transaction as the status change, and void a wrong invoice instead of deleting it. Confirm the rules for your countries with an accountant.

When should an invoice get its number?

At issue time rather than when the draft is created, since a draft can be edited, abandoned or deleted and a number given to it would leave a hole in the series. Taking the next value from a counter row inside the issuing transaction means a failed issue rolls the counter back with it.

How do you stop a payment webhook from being recorded twice?

Store the provider's event ID in a column with a unique constraint and insert with ON CONFLICT DO NOTHING. If the insert changes no rows, the event was already handled and the handler returns success without touching the invoice. Providers redeliver events after timeouts, so the handler must be safe to run any number of times.

How do you build an invoicing backend with Encore?

Declare the database, an invoice-issued topic, a private bucket for PDFs and a cron job in Go next to the endpoints. Issue runs in one database transaction that takes the next number and freezes the invoice, a subscription renders the PDF into the bucket, and the daily job queues reminders from a table with a unique key. Encore provisions an IAM role for the service, or a service account 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