Nov 20, 20268 min read

Build a Daily Interest Accrual Backend for Savings Accounts

Accrue interest on savings and deposit accounts every day from ledger balances, keep sub-cent precision without floating point, make reruns safe, post interest monthly with the rounding remainder carried forward, and schedule it all in TypeScript with Encore.

Illustration for Build a Daily Interest Accrual Backend for Savings Accounts

Interest on a savings account looks like one multiplication, until an auditor asks why an account earned 4.11 instead of 4.12 last month.

An accrual backend works from ledger balances day by day, keeps fractions of a cent without floating point and survives reruns and missed nights. This guide builds it in TypeScript, with daily accruals, monthly posting with a carried remainder, and the schedule.

The Interest Accrual Backend at a Glance

PieceWhat it doesBuilt with
Ledger entriesSource of truth for balances, in integer minor unitsPostgres
Daily accrualOne row per account and day with balance, rate and amountPostgres
Nightly jobAccrues the previous day in batchesCron
Monthly postingRounds the month's accruals, credits the ledger, carries the remainderCron
Backfill endpointAccrues a given date after an outagePrivate API

How Is Daily Interest Calculated?

The common approach is the daily balance method: for each day, multiply the end-of-day balance by the annual rate divided by a day count, then add up the daily amounts until interest is paid. In the US, Regulation DD requires the daily balance or average daily balance method and a daily rate of at least 1/365 of the interest rate. Other products and markets use different day count conventions such as Actual/360, so make the divisor a property of the product, not a constant in code.

A balance of 1,234.56 at 2.5% earns about 0.0846 per day, which does not fit in cents. Store balances as integer minor units, compute daily interest in micro-units (millionths of a minor unit) with integer or exact numeric arithmetic, and only round when the month's interest is posted. The fraction left over is carried into next month instead of being dropped or rounded up.

Accrual should also be idempotent per account and day, so a rerun never pays twice. And the end of day must be defined in one business time zone, since a transaction at 23:30 in Vienna is already tomorrow in UTC.

How Do You Build It with Encore?

Encore

Encore is a backend framework with built-in infrastructure, so the ledger database and the nightly and monthly schedules are declared in the interest service, and Encore provisions the database in your own AWS or GCP account on deploy. Pave Bank built a bank in 9 months with Encore Platform.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs 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 savings --example=ts/hello-world$ cd savings && mkdir -p interest/migrations

Declare the service:

// interest/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("interest");

The schema keeps balances in the ledger, accruals keyed by account and date, and postings keyed by account and month:

-- interest/migrations/1_init.up.sql CREATE TABLE accounts ( id TEXT PRIMARY KEY, currency TEXT NOT NULL, annual_rate_bps INT NOT NULL, -- 250 = 2.50% day_count INT NOT NULL DEFAULT 365, opened_on DATE NOT NULL, closed_on DATE ); CREATE TABLE ledger_entries ( id BIGSERIAL PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts (id), amount_minor BIGINT NOT NULL, -- cents, positive or negative booked_on DATE NOT NULL, kind TEXT NOT NULL, reference TEXT UNIQUE ); CREATE INDEX ledger_account_day_idx ON ledger_entries (account_id, booked_on); CREATE TABLE interest_accruals ( account_id TEXT NOT NULL REFERENCES accounts (id), accrual_date DATE NOT NULL, balance_minor BIGINT NOT NULL, rate_bps INT NOT NULL, amount_micros BIGINT NOT NULL, -- millionths of a cent PRIMARY KEY (account_id, accrual_date) ); CREATE TABLE interest_postings ( account_id TEXT NOT NULL REFERENCES accounts (id), month DATE NOT NULL, -- first day of the month amount_minor BIGINT NOT NULL, carry_micros BIGINT NOT NULL, PRIMARY KEY (account_id, month) );

The rate snapshot on each accrual row matters later: when the rate changes mid-month, the accruals still show what was applied on each day.

Accrue each day

The arithmetic happens in Postgres with numeric and floor, so no amount ever passes through a JavaScript float. Accounts are processed in batches by ID, and the primary key turns a rerun into a no-op:

// interest/accrual.ts import { api } from "encore.dev/api"; import { CronJob } from "encore.dev/cron"; import log from "encore.dev/log"; import { SQLDatabase } from "encore.dev/storage/sqldb"; export const db = new SQLDatabase("interest", { migrations: "./migrations" }); export const BUSINESS_TZ = "Europe/Vienna"; const BATCH = 500; async function accrue(date: string): Promise<number> { let cursor = ""; let inserted = 0; for (;;) { const page = await db.queryRow<{ last: string | null }>` SELECT max(id) AS last FROM ( SELECT id FROM accounts WHERE id > ${cursor} ORDER BY id LIMIT ${BATCH} ) s`; if (!page?.last) break; const res = await db.queryAll<{ account_id: string }>` INSERT INTO interest_accruals (account_id, accrual_date, balance_minor, rate_bps, amount_micros) SELECT a.id, ${date}::date, b.balance, a.annual_rate_bps, floor(GREATEST(b.balance, 0)::numeric * a.annual_rate_bps * 100 / a.day_count) FROM accounts a CROSS JOIN LATERAL ( SELECT COALESCE(sum(l.amount_minor), 0) AS balance FROM ledger_entries l WHERE l.account_id = a.id AND l.booked_on <= ${date}::date ) b WHERE a.id > ${cursor} AND a.id <= ${page.last} AND a.opened_on <= ${date}::date AND (a.closed_on IS NULL OR a.closed_on > ${date}::date) ON CONFLICT (account_id, accrual_date) DO NOTHING RETURNING account_id`; inserted += res.length; cursor = page.last; } return inserted; } // Accrues the previous day in the business time zone. export const accrueYesterday = api({}, async (): Promise<{ accrued: number }> => { const row = await db.queryRow<{ d: string }>` SELECT ((now() AT TIME ZONE ${BUSINESS_TZ})::date - 1)::text AS d`; const accrued = await accrue(row!.d); log.info("interest accrued", { date: row!.d, accrued }); return { accrued }; }); // Backfill after an outage, or replay a day in a test. export const accrueFor = api({}, async ({ date }: { date: string }): Promise<{ accrued: number }> => { return { accrued: await accrue(date) }; }); const _ = new CronJob("accrue-interest", { title: "Accrue daily interest", schedule: "30 0 * * *", endpoint: accrueYesterday, });

The formula is balance × rate_bps / 10,000 / day_count expressed in micro-units, which simplifies to balance × rate_bps × 100 / day_count. Negative balances accrue zero here; overdraft interest belongs in a separate product with its own rate. The cron job schedule is in UTC, so 00:30 UTC is after midnight in Vienna all year.

Post monthly and carry the remainder

On the first of each month, a single statement sums the previous month's micro-units, adds last month's carry, credits whole cents to the ledger and stores the new remainder. The posting key and the ledger reference both make a second run harmless:

// interest/posting.ts import { api } from "encore.dev/api"; import { CronJob } from "encore.dev/cron"; import log from "encore.dev/log"; import { BUSINESS_TZ, db } from "./accrual"; export const postLastMonth = api({}, async (): Promise<{ posted: number }> => { const m = await db.queryRow<{ month: string }>` SELECT (date_trunc('month', (now() AT TIME ZONE ${BUSINESS_TZ})::date) - interval '1 month')::date::text AS month`; const month = m!.month; const rows = await db.queryAll<{ account_id: string }>` WITH totals AS ( SELECT a.account_id, sum(a.amount_micros) + COALESCE(max(p.carry_micros), 0) AS micros FROM interest_accruals a LEFT JOIN interest_postings p ON p.account_id = a.account_id AND p.month = ${month}::date - interval '1 month' WHERE a.accrual_date >= ${month}::date AND a.accrual_date < ${month}::date + interval '1 month' GROUP BY a.account_id ), posted AS ( INSERT INTO interest_postings (account_id, month, amount_minor, carry_micros) SELECT account_id, ${month}::date, div(micros, 1000000), mod(micros, 1000000) FROM totals ON CONFLICT (account_id, month) DO NOTHING RETURNING account_id, month, amount_minor ) INSERT INTO ledger_entries (account_id, amount_minor, booked_on, kind, reference) SELECT account_id, amount_minor, (month + interval '1 month')::date, 'interest', 'interest:' || account_id || ':' || to_char(month, 'YYYY-MM') FROM posted WHERE amount_minor > 0 ON CONFLICT (reference) DO NOTHING RETURNING account_id`; log.info("interest posted", { month, accounts: rows.length }); return { posted: rows.length }; }); const _ = new CronJob("post-interest", { title: "Post last month's interest", schedule: "0 2 1 * *", endpoint: postLastMonth, });

Booking the credit on the first of the new month adds it to that day's balance, which gives monthly compounding. Whether the credit earns interest on the first itself depends on whether posting runs before that night's accrual, so choose the order to match your product terms and cover it in a test.

Run it locally and deploy

Cron jobs do not run with encore run, so locally you call the endpoints directly, for example accrueFor with a date from the local development dashboard or a test, then postLastMonth, and compare the ledger with a spreadsheet. On deploy to your AWS or GCP account, the database becomes RDS or Cloud SQL, and the schedules are managed by the Encore platform, which calls the endpoints in deployed environments. Neither endpoint is exposed, so they are not reachable from the internet.

A new product rule, such as tiered rates above a balance threshold, is a migration plus a change to one SQL expression, and a coding agent can write both, replay a month with accrueFor against the local database and show the diff in totals in the same pull request.

Best fit: fintech and banking teams who want daily accrual and monthly posting they can replay and explain line by line, running against their ledger in their own AWS or GCP account.

Things to Decide Early

  • Day count per product. Actual/365, Actual/360 or Actual/Actual changes every daily amount, so store it on the account or product.
  • Rate changes. Decide whether a new rate applies from the next day or the next statement, and keep historical rates on the accrual rows.
  • Value dates. A deposit booked on Friday may have a value date of Monday; accrue on value dates if your product terms say so.
  • Closed accounts. Post accrued but unpaid interest when an account closes, not on the next monthly run.
  • Reconciliation. Check every month that posted interest plus the carried remainder equals the sum of accruals.

Frequently asked questions

How do banks calculate daily interest on savings accounts?

Most use the daily balance method: take each day's end-of-day balance, multiply it by the annual rate divided by the day count, usually 365, and add up those daily amounts until interest is paid, often monthly. In the US, Regulation DD requires a daily rate of at least 1/365 of the interest rate.

How do I avoid rounding errors in interest calculations?

Never use floating point. Store balances in integer minor units, compute daily interest in a smaller integer unit such as millionths of a cent, and only round when interest is posted, carrying the remainder into the next period so fractions are not lost or paid twice.

How do I make an interest accrual job safe to rerun?

Give each accrual a natural key of account and date with a unique constraint, and insert with ON CONFLICT DO NOTHING. A retried or duplicated run then skips days already accrued, and a backfill for missed days can run the same statement for each date.

How do I schedule interest accrual with Encore?

Declare a CronJob that calls an endpoint every night, for example schedule 30 0 * * *, and have the endpoint accrue the previous business day in batches. Encore cron jobs are managed by the Encore platform and run in deployed environments, so locally you call the endpoint directly.

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