Design the backend that renews insurance policies on time: policy terms as date ranges, a daily renewal scan, re-rating, offer documents, reminder schedules, payment collection, and lapse handling, built by hand on AWS or in TypeScript with Encore in your own account.

A policy renewal looks like one scheduled job and ends up carrying most of an insurance product's retention. Weeks before each term ends, the backend has to re-rate the risk, generate an offer the customer can read, and start reminding them on a schedule that fits the product and the jurisdiction.
It then has to take payment, start the new term on exactly the right day, and lapse the policy cleanly when nobody pays. A renewal that slips by a day leaves a customer uninsured, and a reminder sent to an already renewed customer becomes a complaint.
This guide designs that backend: the data model, the daily scan, offers, reminders, payment and lapses. It starts with a hand-built version on AWS, then builds it in TypeScript with Encore, with the data in your own AWS or GCP account.
Store each policy term as its own row with a date range, the rate table version it was priced with and its premium, rather than overwriting dates on a single policy row. History then answers "what was this customer covered for on March 3", and a renewal is a new term. PostgreSQL range types with an exclusion constraint guarantee that two terms of the same policy never overlap, which turns a class of renewal bugs into a database error.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE policy_terms (
id BIGSERIAL PRIMARY KEY,
policy_id TEXT NOT NULL,
coverage DATERANGE NOT NULL,
rate_version TEXT NOT NULL,
premium_cents BIGINT NOT NULL,
status TEXT NOT NULL DEFAULT 'active', -- active, lapsed, cancelled
EXCLUDE USING GIST (policy_id WITH =, coverage WITH &&)
);
CREATE TABLE renewal_offers (
id BIGSERIAL PRIMARY KEY,
term_id BIGINT NOT NULL UNIQUE REFERENCES policy_terms(id),
premium_cents BIGINT NOT NULL,
document_key TEXT,
status TEXT NOT NULL DEFAULT 'pending', -- pending, rendering, offered, accepted, paid, declined, lapsed
claimed_at TIMESTAMPTZ,
claim_token TEXT,
expires_on DATE NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE renewal_events (
offer_id BIGINT NOT NULL REFERENCES renewal_offers(id),
kind TEXT NOT NULL,
at TIMESTAMPTZ NOT NULL DEFAULT now(),
detail JSONB
);
The unique term_id on offers prevents a second offer for the same term. The daily scan also retries offers that have no document yet, so a failed upload or publish does not permanently suppress the term.
Once a day, select active terms that are still in force, whose coverage ends inside the product's renewal window (often 30 to 60 days ahead), and that have no complete offer yet. For each one, call the rating service with the current rate table version and refreshed inputs (claims since the last term, updated vehicle or property data), store the premium on the offer, and render the offer document. Re-rating can legitimately raise the premium or decline to renew; keep the reasons on the offer, since customers and regulators both ask for them.
Notice periods for premium increases and non-renewals are set by regulators and differ by jurisdiction and line of business, so treat them as configuration per product and state rather than constants, and have compliance own the values. This guide makes no assumption about any specific jurisdiction.
Each offer gets a reminder schedule: for example, at creation, 14 days before expiry, 3 days before, and on the expiry date. Every reminder job checks the offer status first, so an accepted or declined offer silences everything still queued. Payment for customers with a saved method can be taken off-session when the offer is accepted or automatically on the renewal date where the product allows it; the payment provider's webhook moves the offer to paid, and only then does the new term become active. Stripe's guide to saving and reusing payment methods covers the consent the off-session charge depends on.
When the old term ends without payment, the offer enters a grace period if the product has one, and the policy lapses at the end of it. Lapse is an event as well as a status: it triggers a notice, stops claims intake for dates after the end, and may feed reinstatement rules.
Put the policy and renewal tables in RDS for PostgreSQL. An EventBridge Scheduler schedule starts an ECS task each morning that runs the scan, calls the rating service, renders PDFs into a private S3 bucket and enqueues reminder messages on SQS with delays (up to 15 minutes per message, so longer delays need a scheduled reminders table polled by a worker). A worker sends emails through SES, and a webhook endpoint behind an Application Load Balancer receives payment events. Each piece needs an IAM role, a dead-letter queue and alarms, and the scan needs a lock so a retried task does not run twice in parallel.
Encore brings infrastructure from code to this TypeScript service, where the database, the bucket for offer documents, the renewal events topic and the daily cron job are declared in code, and Encore provisions them when you deploy: RDS, S3, SNS and SQS in your own AWS account, or Cloud SQL, Cloud Storage and Pub/Sub on GCP, and Encore provisions an IAM role for the service, or a service account on GCP. encore run starts Postgres, local object storage and in-memory Pub/Sub, so you can run the scan endpoint against seeded terms and follow each offer and reminder in the local trace.
Run in your terminal to get started locally.
// renewals/renewals.ts
import { randomUUID } from "node:crypto";
import { api } from "encore.dev/api";
import { CronJob } from "encore.dev/cron";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Bucket } from "encore.dev/storage/objects";
import { Topic, Subscription } from "encore.dev/pubsub";
import { rating } from "~encore/clients";
const db = new SQLDatabase("renewals", { migrations: "./migrations" });
const offerDocs = new Bucket("renewal-offers", { versioned: false });
export interface RenewalEvent {
offerId: number;
kind: "offered" | "reminder_due" | "paid" | "lapsed";
}
export const renewalEvents = new Topic<RenewalEvent>("renewal-events", {
deliveryGuarantee: "at-least-once",
});
// Called by the cron job once a day; safe to run again.
export const scan = api({ expose: false }, async (): Promise<{ offered: number }> => {
const due = await db.queryAll<{ id: number; policy_id: string; ends: string; offer_id: number | null }>`
SELECT t.id, t.policy_id, upper(t.coverage)::text AS ends, o.id AS offer_id
FROM policy_terms t
LEFT JOIN renewal_offers o ON o.term_id = t.id
WHERE t.status = 'active' AND (o.id IS NULL OR (o.document_key IS NULL AND (o.status = 'pending' OR (o.status = 'rendering' AND o.claimed_at < now() - interval '5 minutes'))))
AND upper(t.coverage) > current_date
AND upper(t.coverage) <= current_date + 45`;
let offered = 0;
for (const term of due) {
const quote = await rating.reRate({ policyId: term.policy_id, termId: term.id });
let offerId = term.offer_id;
if (!offerId) {
const row = await db.queryRow<{ id: number }>`
INSERT INTO renewal_offers (term_id, premium_cents, expires_on)
VALUES (${term.id}, ${quote.premiumCents}, ${term.ends}::date)
ON CONFLICT (term_id) DO NOTHING
RETURNING id`;
if (!row) {
const existing = await db.queryRow<{ id: number; document_key: string | null; status: string }>`
SELECT id, document_key, status FROM renewal_offers WHERE term_id = ${term.id}`;
if (!existing || existing.document_key || (existing.status !== "pending" && existing.status !== "rendering")) continue;
offerId = existing.id;
} else {
offerId = row.id;
}
}
const claimToken = randomUUID();
const claimed = await db.queryRow<{ id: number }>`
UPDATE renewal_offers
SET status = 'rendering', claimed_at = now(), claim_token = ${claimToken}
WHERE id = ${offerId} AND document_key IS NULL
AND (status = 'pending'
OR (status = 'rendering' AND claimed_at < now() - interval '5 minutes'))
RETURNING id`;
if (!claimed) continue;
const key = `offers/${offerId}-${claimToken}.pdf`;
await offerDocs.upload(key, quote.documentPdf, { contentType: "application/pdf" });
const updated = await db.queryRow<{ id: number }>`
UPDATE renewal_offers
SET document_key = ${key}, status = 'offered'
WHERE id = ${offerId} AND status = 'rendering' AND claim_token = ${claimToken}
RETURNING id`;
if (!updated) continue;
await renewalEvents.publish({ offerId, kind: "offered" });
offered++;
}
return { offered };
});
const _ = new CronJob("renewal-scan", {
title: "Create renewal offers for terms in the window",
schedule: "0 5 * * *", // 05:00 UTC daily
endpoint: scan,
});
const __ = new Subscription(renewalEvents, "notify", {
handler: async ({ offerId, kind }) => {
const offer = await db.queryRow<{ status: string }>`
SELECT status FROM renewal_offers WHERE id = ${offerId}`;
if (!offer) return;
if (kind === "reminder_due" && offer.status !== "offered") return; // decided already
await db.exec`INSERT INTO renewal_events (offer_id, kind) VALUES (${offerId}, ${kind})`;
// Send the email or SMS for this event through your provider.
},
retryPolicy: { maxRetries: 10 },
});
The cron job is Encore platform managed: it runs in deployed environments and not under encore run or in preview environments, so locally you exercise it from a test that calls scan() under encore test, which sets up the database in test mode. A second daily cron job can publish reminder_due events for offers at each reminder offset and move unpaid offers past their grace period to lapsed; the payment provider's webhook lands on a raw endpoint that verifies the signature and publishes paid. The rating service is a separate Encore service called through the generated client, so the renewal scan and the new business quote flow share one rating implementation.
A coding agent working in this repository can change a reminder schedule or add a product's grace period as a code change, then replay the scan locally against seeded terms before review.
Best fit: insurers, MGAs and insurtech teams that renew policies on a term basis and want offers, reminders and lapses in their own AWS or GCP account.
A daily job finds policy terms that expire within the renewal window, re-rates each one with current rates and the latest risk data, and creates a renewal offer with a document. Reminders go out on a schedule until the customer accepts, pays or declines. Accepted offers become a new policy term that starts the day the old one ends; unpaid ones move into a grace period and then lapse, with every step recorded for audit.
Declare a Postgres database, an object storage bucket for offer documents, a Pub/Sub topic for renewal events and a cron job for the daily scan in TypeScript. Subscribers send reminders and handle lapses. On deploy to your own AWS account Encore provisions RDS, S3, SNS and SQS, and an IAM role for the service; the cron schedule is managed by the Encore platform.
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.