Updated Dec 1, 202610 min read

Build an Insurance Premium Billing and Grace Period Backend

How to turn an annual premium into an installment schedule, apply payments exactly once, track grace periods, send a pending lapse notice once per missed installment, lapse or reinstate the policy, and run it on AWS or GCP.

Illustration for Build an Insurance Premium Billing and Grace Period Backend

A policy system can bill an annual premium from one column until the first customer pays monthly. Each installment then needs a due date and a balance, a processor may deliver the same payment twice, and a missed payment starts a grace period that decides whether a later claim is covered.

This guide builds that billing service with installment schedules, idempotent payments, a daily grace period sweep and lapse notices that go out once.

What does premium billing need to track?

PieceWhat to decide
ScheduleThe annual premium split into 1, 2, 4 or 12 installments, with the rounding remainder on the first one
Due datesEvenly spaced from the policy start date
PaymentsEach one keyed by the processor's reference so a duplicate is ignored
AllocationPayments applied to the oldest open installment first
Grace periodThe number of days after a due date during which coverage stays in force, set per policy
NoticesOne pending lapse notice per missed installment, sent after the grace period ends
Lapse and reinstatementA notice period before the policy lapses, and a return to active when the arrears are paid

The grace period comes from the policy form and the regulator. The NAIC Uniform Individual Accident and Sickness Policy Provision Law requires at least 7 days for weekly premiums, 10 for monthly premiums and 31 for all other policies, and property and casualty lines follow state cancellation statutes with their own notice periods, so both numbers belong in configuration on the policy rather than in code.

How do you build it without a framework?

The schedule is a single INSERT ... SELECT over generate_series, which writes every installment for a policy in one statement and puts the remainder of the integer division on the first row. A payment is a transaction that inserts the processor reference with ON CONFLICT DO NOTHING, locks the open installments in order with FOR UPDATE and applies the amount until it runs out, following the Postgres rules for explicit row locks. Around that you need a daily job that finds installments past their grace period, a queue that delivers each notice to the document or email service with retries, and a database that behaves the same on a laptop and in production.

How does Encore build the billing service?

Encore

Encore brings infrastructure from code, so the billing tables, the lapse notice topic and the daily sweep are declared next to the endpoints and created in your own AWS or GCP account on deploy. On AWS that is Fargate with RDS and SNS with SQS, as the AWS infrastructure docs list, and on GCP it is Cloud Run with Cloud SQL and Pub/Sub.

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 premiums --example=hello-world$ cd premiums && mkdir -p billing/migrations

The service creates the schedule with the policy, applies payments inside one transaction, and runs a daily sweep that publishes an event for every installment past its grace period. The subscriber records the notice with a guarded update, so a second delivery of the same event sends nothing, and the sweep lapses policies whose notice period has run out:

// billing/billing.go package billing import ( "context" "errors" "time" "encore.dev/beta/errs" "encore.dev/cron" "encore.dev/pubsub" "encore.dev/rlog" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("billing", sqldb.DatabaseConfig{Migrations: "./migrations"}) type CreatePolicyParams struct { Holder string `json:"holder"` AnnualCents int64 `json:"annual_cents"` Installments int `json:"installments"` GraceDays int `json:"grace_days"` StartsOn string `json:"starts_on"` // YYYY-MM-DD } type Policy struct { ID int64 `json:"id"` Status string `json:"status"` Due int64 `json:"due_cents"` } //encore:api public method=POST path=/policies func CreatePolicy(ctx context.Context, p *CreatePolicyParams) (*Policy, error) { switch p.Installments { case 1, 2, 4, 12: default: return nil, &errs.Error{Code: errs.InvalidArgument, Message: "installments must be 1, 2, 4 or 12"} } if p.AnnualCents <= 0 || p.GraceDays < 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "invalid premium or grace period"} } start, err := time.Parse("2006-01-02", p.StartsOn) if err != nil { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "starts_on must be YYYY-MM-DD"} } tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() var id int64 err = tx.QueryRow(ctx, ` INSERT INTO policies (holder, annual_cents, grace_days) VALUES ($1, $2, $3) RETURNING id`, p.Holder, p.AnnualCents, p.GraceDays).Scan(&id) if err != nil { return nil, err } n := int64(p.Installments) _, err = tx.Exec(ctx, ` INSERT INTO installments (policy_id, seq, due_on, amount_cents) SELECT $1, g, ($2::date + make_interval(months => (g - 1) * $3::int))::date, $4::bigint / $5::int + CASE WHEN g = 1 THEN $4::bigint % $5::int ELSE 0 END FROM generate_series(1, $5::int) AS g`, id, start, 12/n, p.AnnualCents, n) if err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, err } return GetPolicy(ctx, id) } //encore:api public method=GET path=/policies/:id func GetPolicy(ctx context.Context, id int64) (*Policy, error) { p := &Policy{ID: id} err := db.QueryRow(ctx, ` SELECT p.status, COALESCE(sum(i.amount_cents - i.paid_cents) FILTER (WHERE i.due_on <= current_date), 0) FROM policies p LEFT JOIN installments i ON i.policy_id = p.id WHERE p.id = $1 GROUP BY p.status`, id).Scan(&p.Status, &p.Due) if errors.Is(err, sqldb.ErrNoRows) { return nil, &errs.Error{Code: errs.NotFound, Message: "policy not found"} } if err != nil { return nil, err } return p, nil } type PaymentParams struct { Reference string `json:"reference"` // the payment processor's ID AmountCents int64 `json:"amount_cents"` } //encore:api public method=POST path=/policies/:id/payments func Pay(ctx context.Context, id int64, p *PaymentParams) (*Policy, error) { if p.Reference == "" || p.AmountCents <= 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "reference and a positive amount are required"} } tx, err := db.Begin(ctx) if err != nil { return nil, err } defer tx.Rollback() res, err := tx.Exec(ctx, ` INSERT INTO payments (reference, policy_id, amount_cents) SELECT $1, id, $3 FROM policies WHERE id = $2 AND status <> 'lapsed' ON CONFLICT (reference) DO NOTHING`, p.Reference, id, p.AmountCents) if err != nil { return nil, err } if res.RowsAffected() == 0 { // A duplicate delivery, or a lapsed policy that needs a reinstatement review. return GetPolicy(ctx, id) } rows, err := tx.Query(ctx, ` SELECT seq, amount_cents - paid_cents FROM installments WHERE policy_id = $1 AND paid_cents < amount_cents ORDER BY seq FOR UPDATE`, id) if err != nil { return nil, err } type open struct{ seq, left int64 } var opens []open for rows.Next() { var o open if err := rows.Scan(&o.seq, &o.left); err != nil { rows.Close() return nil, err } opens = append(opens, o) } rows.Close() if err := rows.Err(); err != nil { return nil, err } remaining := p.AmountCents for _, o := range opens { if remaining == 0 { break } apply := min(remaining, o.left) if _, err := tx.Exec(ctx, ` UPDATE installments SET paid_cents = paid_cents + $3 WHERE policy_id = $1 AND seq = $2`, id, o.seq, apply); err != nil { return nil, err } remaining -= apply } // Reinstate when nothing is left past its grace period. _, err = tx.Exec(ctx, ` UPDATE policies p SET status = 'active' WHERE p.id = $1 AND p.status = 'lapse_pending' AND NOT EXISTS ( SELECT 1 FROM installments i WHERE i.policy_id = p.id AND i.paid_cents < i.amount_cents AND i.due_on + p.grace_days < current_date)`, id) if err != nil { return nil, err } if err := tx.Commit(); err != nil { return nil, err } return GetPolicy(ctx, id) } type GraceExpired struct { PolicyID int64 `json:"policy_id"` Seq int64 `json:"seq"` } var graceExpired = pubsub.NewTopic[*GraceExpired]("premium-grace-expired", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) // noticeDays is the notice period between the pending lapse notice and the lapse. // Set it from the policy form and the rules of each state you write in. const noticeDays = 10 //encore:api private func Sweep(ctx context.Context) error { _, err := db.Exec(ctx, ` UPDATE policies p SET status = 'lapsed' WHERE p.status = 'lapse_pending' AND EXISTS ( SELECT 1 FROM installments i WHERE i.policy_id = p.id AND i.paid_cents < i.amount_cents AND i.lapse_notice_at < now() - make_interval(days => $1))`, noticeDays) if err != nil { return err } rows, err := db.Query(ctx, ` SELECT i.policy_id, i.seq FROM installments i JOIN policies p ON p.id = i.policy_id WHERE p.status IN ('active', 'lapse_pending') AND i.paid_cents < i.amount_cents AND i.lapse_notice_at IS NULL AND i.due_on + p.grace_days < current_date LIMIT 1000`) if err != nil { return err } var due []*GraceExpired for rows.Next() { e := &GraceExpired{} if err := rows.Scan(&e.PolicyID, &e.Seq); err != nil { rows.Close() return err } due = append(due, e) } rows.Close() if err := rows.Err(); err != nil { return err } for _, e := range due { if _, err := graceExpired.Publish(ctx, e); err != nil { return err } } return nil } var _ = cron.NewJob("premium-billing-sweep", cron.JobConfig{ Title: "Lapse policies and queue pending lapse notices", Schedule: "0 5 * * *", Endpoint: Sweep, }) var _ = pubsub.NewSubscription(graceExpired, "send-lapse-notice", pubsub.SubscriptionConfig[*GraceExpired]{ Handler: func(ctx context.Context, e *GraceExpired) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() res, err := tx.Exec(ctx, ` UPDATE installments SET lapse_notice_at = now() WHERE policy_id = $1 AND seq = $2 AND lapse_notice_at IS NULL AND paid_cents < amount_cents`, e.PolicyID, e.Seq) if err != nil { return err } if res.RowsAffected() == 0 { return nil // already noticed, or paid since the sweep ran } if _, err := tx.Exec(ctx, ` UPDATE policies SET status = 'lapse_pending' WHERE id = $1 AND status = 'active'`, e.PolicyID); err != nil { return err } if err := tx.Commit(); err != nil { return err } rlog.Info("pending lapse notice", "policy", e.PolicyID, "installment", e.Seq) return nil }, RetryPolicy: &pubsub.RetryPolicy{MinBackoff: 30 * time.Second, MaxBackoff: 30 * time.Minute, MaxRetries: 8}, })
-- billing/migrations/1_create_tables.up.sql CREATE TABLE policies ( id BIGSERIAL PRIMARY KEY, holder TEXT NOT NULL, annual_cents BIGINT NOT NULL CHECK (annual_cents > 0), grace_days INT NOT NULL CHECK (grace_days >= 0), status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'lapse_pending', 'lapsed')), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE installments ( policy_id BIGINT NOT NULL REFERENCES policies (id), seq BIGINT NOT NULL, due_on DATE NOT NULL, amount_cents BIGINT NOT NULL CHECK (amount_cents > 0), paid_cents BIGINT NOT NULL DEFAULT 0 CHECK (paid_cents >= 0 AND paid_cents <= amount_cents), lapse_notice_at TIMESTAMPTZ, PRIMARY KEY (policy_id, seq) ); CREATE INDEX installments_open ON installments (due_on) WHERE paid_cents < amount_cents; CREATE TABLE payments ( reference TEXT PRIMARY KEY, policy_id BIGINT NOT NULL REFERENCES policies (id), amount_cents BIGINT NOT NULL CHECK (amount_cents > 0), received_at TIMESTAMPTZ NOT NULL DEFAULT now() );

encore run starts Postgres locally and applies the migration, so creating a monthly policy, paying with the same reference twice and checking the balance can be driven with curl. Cron jobs do not run locally, so the sweep is tested by calling its endpoint from the local development dashboard after back-dating an installment. The database docs cover transactions and migrations, the Pub/Sub docs cover retries and the dead-letter queue, and the cron docs cover schedules, which the Encore platform manages.

Deploying follows Connect your cloud account and a push, and the database, the topic and the schedule are created in your account with the policy and payment data kept there. When an AI coding agent adds a past-due reminder before the grace period ends, the new column, the sweep query and the subscriber are one change it can run locally against the same Postgres schema.

Best fit: Insurance engineering teams that bill premiums in installments and want schedules, payments and grace period rules in a service that runs in their own AWS or GCP account.

What should you check before going live?

Overpayments stop at the last open installment in this example, so decide whether the rest becomes a credit balance or a refund and record it in a ledger table. Notices are logged here, and the real sender should pass the policy and installment as an idempotency key to the document or email provider, since a failure after the commit is not retried. Grace and notice periods differ by line of business and state, so load them per policy form instead of a constant, and keep payments on lapsed policies in a review queue because reinstatement rules often require an application. Add authorization to the payment endpoint, or move it behind the processor webhook with a signature check, and write an audit row for every status change.

Frequently asked questions

What is a grace period in insurance premium billing?

It is the time after a premium falls due during which the policy stays in force if the premium is paid. The NAIC model law for individual accident and sickness policies sets a minimum of 7 days for weekly premiums, 10 days for monthly premiums and 31 days for others, and other lines and states set their own rules.

How should a billing system split an annual premium into installments?

Divide the annual premium in cents by the number of installments, add the remainder to the first installment so the total matches exactly, and space the due dates evenly from the policy start date. Store each installment as its own row with its due date, amount and amount paid.

How do I avoid applying the same premium payment twice?

Store each payment under the reference from the payment provider as a primary key and apply it in the same transaction. A webhook or a retry that delivers the same reference again hits the conflict and leaves the balances unchanged.

How do I run a premium billing service in my own AWS or GCP account?

Build it with Encore, declaring the database, the lapse notice topic and the daily billing sweep cron job in code, and deploy to your own AWS or GCP account. encore run starts Postgres locally, so payments and grace period transitions can be tested before deploying. Cron jobs do not run locally or in preview environments.

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