Nov 16, 202614 min read

Insurance Policy Quoting Backend: Rate Books, Expiring Quotes and Bind

Design versioned rate books, quotes that lock a premium, an expiry enforced at bind, quote and binder documents in private storage, then implement the flow in TypeScript.

Illustration for Insurance Policy Quoting Backend: Rate Books, Expiring Quotes and Bind

A quote is a priced offer that expires, and a bind is the step that turns that offer into coverage at the rates already shown. Teams get into trouble when a later rate change is applied at bind, or when two binders are issued for the same quote after a double click.

This guide designs a policy quoting backend: versioned rate books, quotes that carry the book they used, an expiry enforced at bind, and the quote and binder documents stored as objects. It starts with the data model and the bind rules, then shows the design by hand on AWS and in TypeScript with Encore. Policy and quote records stay in your own AWS or GCP account. Talk to your compliance team about any licensing or regulatory requirements that apply to you.

Unlike a freight rate shop, there are no live carrier calls at quote time: the price comes from a rate book you already published, and bind locks that price rather than asking a third party for a new one.

The Quoting Backend at a Glance

JobPatternHand-built on AWSWith Encore in your AWS account
Rate bookVersioned book with an effective time, never edited in placeRDS for PostgreSQLEncore database on RDS
QuoteInputs hash, premium, rate_book_id and expires_atSame databaseSame database
DocumentsQuote PDF and binder PDF in a private bucketS3 bucket and presigned URLsEncore bucket with signed URLs
Bind onceConditional UPDATE plus a unique policy row per quoteSame databaseSame database
ExpiryDaily sweep of quotes still in quoted past expires_atEventBridge Scheduler or an ECS scheduled taskCron job, Encore platform Managed
NoticesQuoted, bound or expired, each sent onceSNS topic and SQS queuePub/Sub topic and subscription

Rate Books and Locked Premiums

A rate book is a published set of prices for a product, with an effective_at and, later, a retired_at. New quotes use the current book for that product. Old quotes keep the rate_book_id they were priced with, even after that book is retired, so a bind that arrives before expires_at still uses the premium the applicant saw.

Do not update lines in a live book; issue a new book, point new quotes at it, and retire the previous one. An in-place edit is how two quotes issued minutes apart disagree, and how an audit cannot say which numbers produced a binder.

The quote row stores enough to reproduce the price: the book, the structured inputs, a hash of those inputs, and the premium. If the applicant changes a rating input, that is a new quote, not an update in place. Under Read Committed this is a plain insert, and the constraint that matters is at bind time, not at quote time.

CREATE TABLE rate_books ( id TEXT PRIMARY KEY, product_code TEXT NOT NULL, effective_at TIMESTAMPTZ NOT NULL, retired_at TIMESTAMPTZ ); CREATE TABLE rate_lines ( rate_book_id TEXT NOT NULL REFERENCES rate_books (id), region TEXT NOT NULL, coverage TEXT NOT NULL, base_cents INT NOT NULL CHECK (base_cents >= 0), PRIMARY KEY (rate_book_id, region, coverage) ); CREATE TABLE quotes ( id TEXT PRIMARY KEY, applicant_id TEXT NOT NULL, product_code TEXT NOT NULL, rate_book_id TEXT NOT NULL REFERENCES rate_books (id), inputs JSONB NOT NULL, inputs_hash TEXT NOT NULL, premium_cents INT NOT NULL CHECK (premium_cents >= 0), status TEXT NOT NULL CHECK (status IN ('quoted', 'bound', 'expired', 'declined')), expires_at TIMESTAMPTZ NOT NULL, bound_at TIMESTAMPTZ, policy_id TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE policies ( id TEXT PRIMARY KEY, quote_id TEXT NOT NULL UNIQUE REFERENCES quotes (id), rate_book_id TEXT NOT NULL REFERENCES rate_books (id), premium_cents INT NOT NULL, bound_at TIMESTAMPTZ NOT NULL ); CREATE TABLE sent_notices ( quote_id TEXT NOT NULL, kind TEXT NOT NULL, PRIMARY KEY (quote_id, kind) );

A practical set of quote statuses is:

StatusMeaningTypical next steps
quotedA priced offer is in date and has not been bound.bound, expired, declined
boundA policy row exists and the binder document has been stored.Terminal
expiredexpires_at passed with no bind.Terminal; the applicant starts a new quote
declinedUnderwriting refused the offer, or the applicant withdrew it.Terminal

Bind is a claim on the quote row, then an insert into policies. The premium on the policy is copied from the quote, not computed again.

UPDATE quotes SET status = 'bound', bound_at = now(), policy_id = $2 WHERE id = $1 AND status = 'quoted' AND expires_at > now() RETURNING rate_book_id, premium_cents; INSERT INTO policies (id, quote_id, rate_book_id, premium_cents, bound_at) VALUES ($2, $1, $3, $4, now());

If the UPDATE returns no row, look up an existing policy for that quote_id and return it when the request is a retry, or return an error when the quote is expired, declined or missing. The unique constraint on policies.quote_id is the backstop if two binds race past the UPDATE; one insert succeeds and the other is rejected, and the loser reads the winner's policy.

Pick an expiry when the quote is issued and store it on the row. Do not rely on a convention such as "30 days" in the application only, because a bind at day 31 has to fail in the database even if a client clock is wrong. The daily expiry job marks leftover quoted rows expired with FOR UPDATE SKIP LOCKED, so two overlapping runs cannot notify the same quote twice.

Quote and Binder Documents

After a quote is stored, write a PDF (or the document format you use) to a private bucket at a stable key such as quotes/<quote_id>/quote.pdf. After a successful bind, write the binder at policies/<policy_id>/binder.pdf. Case owners and applicants receive short-lived signed download URLs, not public objects.

Write each document once: if the generator crashes after the bind commits, a retry should check that the object exists and only then upload, so a second bind request does not replace a binder that has already been issued. Version the bucket so an accidental overwrite is recoverable.

Third-party data used in rating, such as a credit or motor-vehicle report, belongs in the inputs JSON and, if you retain the source file, in the same private bucket under the quote ID. Those files are underwriting records, not public documents, and their retention is a policy you set with your counsel, not a default in this service.

How Do You Build It by Hand on AWS?

The design above does not depend on a particular application framework. A service you build and operate yourself on AWS can implement every part of it.

  1. Store rate books, quotes and policies. RDS for PostgreSQL holds the schema, and the API runs on ECS Fargate in private subnets that can reach the database. You write the task role, the security groups and the DATABASE_URL (or a secrets-backed equivalent), and you apply migrations as a step in the deploy so two replicas do not race at startup.
  2. Issue a quote. The handler selects the current rate book for the product, computes the premium from rate_lines (and any surcharges your book defines), inserts the quote and writes the quote PDF to a private S3 bucket with public access blocked. The task role needs write access to that bucket, and you maintain the bucket policy.
  3. Bind once. A bind endpoint runs the conditional UPDATE, inserts the policy, and writes the binder PDF to the same bucket, and retried requests return the existing policy. If a rating vendor is involved at quote time only, its API key lives in Secrets Manager and is not called again at bind.
  4. Sweep expired quotes. An EventBridge Scheduler rule, or an ECS scheduled task, runs once a day, finds quoted rows past expires_at, and marks them expired.
  5. Notify. Quote, bind and expiry notices go to SNS, and a worker on an SQS queue sends each one once, keyed by quote and kind, which is what sent_notices enforces.

You also write the Dockerfile, the load balancer and the deployment pipeline. This path is explicit and portable, and the connecting work (IAM, networking, secret injection, the scheduler and the deploy graph) stays yours to keep in sync with the rate books as they change.

How Do You Build It with Encore?

Encore

Encore is a backend framework with built-in infrastructure for TypeScript and Go. The quoting database, the documents bucket, the notices topic and the expiry job are declared in the service code. When the app deploys to your own AWS account, Encore provisions RDS, S3, SNS and SQS, as the AWS infrastructure docs list. The same code deploys to GCP with Cloud SQL, Cloud Storage and Pub/Sub. Encore provisions an IAM role for the service, or a service account on GCP.

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.

A coding agent working in this repository adds a table or a bucket in the same change as the handler, and encore run starts Postgres locally and stores documents on disk so quote and bind can be called before anything is pushed. Cron jobs do not run in local development or preview environments, so the expiry sweep is tested by calling its endpoint from the local dashboard.

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

Put the schema from the data model section in quoting/migrations/1_quoting.up.sql. If a later iteration calls a rating vendor, set that key with encore secret set so the value stays out of the repository, where a coding agent working in the code sees the secret's name but not its value.

Issue a Quote and Bind It Once

The handlers below price a quote from the current rate book, write a document at a stable key, and bind without recalculating the premium. The expiry job claims due quotes one at a time.

// quoting/quoting.ts import { api, APIError, Gateway } from "encore.dev/api"; import { authHandler, Header } from "encore.dev/auth"; import { secret } from "encore.dev/config"; import { CronJob } from "encore.dev/cron"; import { Subscription, Topic } from "encore.dev/pubsub"; import { Bucket } from "encore.dev/storage/objects"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import log from "encore.dev/log"; import { getAuthData } from "~encore/auth"; import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto"; const db = new SQLDatabase("quoting", { migrations: "./migrations" }); const documents = new Bucket("policy-documents", { versioned: true }); const sessionKey = secret("SessionKey"); interface AuthParams { authorization: Header<"Authorization">; } interface AuthData { userID: string; } // Tokens are "<user id>.<unix expiry>.<hex HMAC of id.expiry>", issued by your login flow. export const auth = authHandler<AuthParams, AuthData>(async (params) => { const token = (params.authorization ?? "").replace(/^Bearer\s+/i, ""); const parts = token.split("."); if (parts.length !== 3) throw APIError.unauthenticated("invalid token"); const [id, expStr, sig] = parts; const exp = Number(expStr); if (!id || !Number.isFinite(exp) || exp <= Math.floor(Date.now() / 1000)) { throw APIError.unauthenticated("invalid token"); } const want = createHmac("sha256", sessionKey()).update(`${id}.${expStr}`).digest("hex"); const a = Buffer.from(sig); const b = Buffer.from(want); if (a.length !== b.length || !timingSafeEqual(a, b)) { throw APIError.unauthenticated("invalid token"); } return { userID: id }; }); export const gateway = new Gateway({ authHandler: auth }); const QUOTE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days, stored on the row export interface QuoteNotice { kind: "quoted" | "bound" | "expired"; quoteId: string; policyId?: string; } export const notices = new Topic<QuoteNotice>("quote-notices", { deliveryGuarantee: "at-least-once", }); interface QuoteParams { productCode: string; region: string; coverage: string; } interface QuoteResult { quoteId: string; premiumCents: number; expiresAt: string; documentUrl: string; } export const issueQuote = api( { expose: true, auth: true, method: "POST", path: "/quotes" }, async (p: QuoteParams): Promise<QuoteResult> => { const applicantId = getAuthData()!.userID; const book = await db.queryRow<{ id: string; base_cents: number }>` SELECT b.id, l.base_cents FROM rate_books b JOIN rate_lines l ON l.rate_book_id = b.id WHERE b.product_code = ${p.productCode} AND b.effective_at <= now() AND (b.retired_at IS NULL OR b.retired_at > now()) AND l.region = ${p.region} AND l.coverage = ${p.coverage} ORDER BY b.effective_at DESC LIMIT 1`; if (!book) throw APIError.failedPrecondition("no effective rate book for this product"); const inputs = { productCode: p.productCode, region: p.region, coverage: p.coverage }; const inputsHash = createHash("sha256").update(JSON.stringify(inputs)).digest("hex"); const quoteId = randomUUID(); const expiresAt = new Date(Date.now() + QUOTE_TTL_MS); await db.exec` INSERT INTO quotes ( id, applicant_id, product_code, rate_book_id, inputs, inputs_hash, premium_cents, status, expires_at ) VALUES ( ${quoteId}, ${applicantId}, ${p.productCode}, ${book.id}, ${JSON.stringify(inputs)}::jsonb, ${inputsHash}, ${book.base_cents}, 'quoted', ${expiresAt} )`; const pdf = await renderQuotePdf(quoteId, book.base_cents); const key = `quotes/${quoteId}/quote.pdf`; if (!(await documents.exists(key))) { await documents.upload(key, pdf, { contentType: "application/pdf" }); } const signed = await documents.signedDownloadUrl(key, { ttl: 15 * 60 }); await notices.publish({ kind: "quoted", quoteId }); return { quoteId, premiumCents: book.base_cents, expiresAt: expiresAt.toISOString(), documentUrl: signed.url, }; }, ); interface BindParams { quoteId: string; } interface BindResult { policyId: string; premiumCents: number; documentUrl: string; } export const bindQuote = api( { expose: true, auth: true, method: "POST", path: "/quotes/:quoteId/bind" }, async ({ quoteId }: BindParams): Promise<BindResult> => { const applicantId = getAuthData()!.userID; const existing = await db.queryRow<{ id: string; premium_cents: number }>` SELECT p.id, p.premium_cents FROM policies p JOIN quotes q ON q.id = p.quote_id WHERE p.quote_id = ${quoteId} AND q.applicant_id = ${applicantId}`; if (existing) { const key = `policies/${existing.id}/binder.pdf`; if (!(await documents.exists(key))) { const pdf = await renderBinderPdf(existing.id, existing.premium_cents); await documents.upload(key, pdf, { contentType: "application/pdf" }); } return await binderResponse(existing.id, existing.premium_cents); } const policyId = randomUUID(); await using tx = await db.begin(); const claimed = await tx.queryRow<{ rate_book_id: string; premium_cents: number }>` UPDATE quotes SET status = 'bound', bound_at = now(), policy_id = ${policyId} WHERE id = ${quoteId} AND applicant_id = ${applicantId} AND status = 'quoted' AND expires_at > now() RETURNING rate_book_id, premium_cents`; if (!claimed) { throw APIError.failedPrecondition("quote is not open to bind"); } await tx.exec` INSERT INTO policies (id, quote_id, rate_book_id, premium_cents, bound_at) VALUES (${policyId}, ${quoteId}, ${claimed.rate_book_id}, ${claimed.premium_cents}, now())`; await tx.commit(); const pdf = await renderBinderPdf(policyId, claimed.premium_cents); const key = `policies/${policyId}/binder.pdf`; if (!(await documents.exists(key))) { await documents.upload(key, pdf, { contentType: "application/pdf" }); } await notices.publish({ kind: "bound", quoteId, policyId }); return await binderResponse(policyId, claimed.premium_cents); }, ); async function binderResponse(policyId: string, premiumCents: number): Promise<BindResult> { const key = `policies/${policyId}/binder.pdf`; if (!(await documents.exists(key))) { throw APIError.notFound("binder not stored yet"); } const signed = await documents.signedDownloadUrl(key, { ttl: 15 * 60 }); return { policyId, premiumCents, documentUrl: signed.url }; } export const expireQuotes = api({}, async (): Promise<{ expired: number }> => { let expired = 0; while (expired < 200) { await using tx = await db.begin(); const row = await tx.queryRow<{ id: string }>` UPDATE quotes SET status = 'expired' WHERE id = ( SELECT id FROM quotes WHERE status = 'quoted' AND expires_at <= now() ORDER BY expires_at LIMIT 1 FOR UPDATE SKIP LOCKED ) RETURNING id`; if (!row) break; await tx.commit(); await notices.publish({ kind: "expired", quoteId: row.id }); expired++; } return { expired }; }); const _ = new CronJob("expire-open-quotes", { title: "Expire unbound insurance quotes", schedule: "0 6 * * *", endpoint: expireQuotes, }); const __ = new Subscription(notices, "email-applicant", { handler: async (n) => { const first = await db.queryRow` INSERT INTO sent_notices (quote_id, kind) VALUES (${n.quoteId}, ${n.kind}) ON CONFLICT DO NOTHING RETURNING quote_id`; if (!first) return; log.info("quote notice", { kind: n.kind, quote: n.quoteId, policy: n.policyId }); }, }); async function renderQuotePdf(quoteId: string, premiumCents: number): Promise<Buffer> { return Buffer.from(`Quote ${quoteId} premium ${premiumCents}\n`); } async function renderBinderPdf(policyId: string, premiumCents: number): Promise<Buffer> { return Buffer.from(`Binder ${policyId} premium ${premiumCents}\n`); }

The database docs cover migrations and transactions, the object storage docs cover versioned buckets and signed URLs, the Pub/Sub docs cover topics, and the cron job docs cover schedules. encore run starts Postgres locally and stores documents on disk, so you can issue a quote, bind it and call expireQuotes from the local development dashboard. Cron jobs do not run locally or in preview environments; once deployed, the Encore platform calls the endpoint at 06:00 UTC.

Schedules use a cron expression evaluated in UTC, as 0 6 * * * does here. The 30-day window is a value stored on each quote, not a rule the job recomputes, so a product with a shorter offer period can use a different expires_at without changing the sweep.

Deploy to Your AWS Account

Connect your AWS account as described in Connect your cloud account, create an environment and run git push encore. Encore builds the Docker image, so you do not maintain a Dockerfile. When a coding agent later adds a surcharge line to a rate book, the change is a migration and a query in issueQuote, and it reaches production through the same review and deploy as any other pull request.

Things to Decide Early

  • How long a quote stays bindable. Thirty days is a starting point, not a rule. Store the expiry on the quote and enforce it in the bind UPDATE, including for products that use a shorter window.
  • What bind requires besides an open quote. Payment, signatures or an underwriting checklist belong in front of bindQuote. The SQL above only claims the offer.
  • Correcting a bound policy. A mid-term change is an endorsement, which is a new record, not an update to the binder PDF or a second bind of the same quote.
  • Publishing after commit. The code publishes notices after the transaction commits, so a crash between the two loses one email but never sends one for a rolled-back change. A transactional outbox table removes that gap if every email must go out.

Frequently asked questions

What is the difference between a quote and a bind?

A quote is a priced offer that expires, and a bind turns that offer into coverage at the premium and rate book already shown on the quote. The bind step must not recalculate the premium, and it must refuse a quote that has expired or has already been bound.

How do you stop a quote from being bound twice?

Insert one policy row per quote with a unique constraint on quote_id, and flip the quote to bound with a conditional UPDATE that requires status quoted and expires_at still in the future. A second request finds no quote row to update and returns the existing policy if one is already on file.

Should the premium be recalculated when a quote is bound?

No. The quote stored the rate book and the premium that were shown to the applicant. Recalculating at bind is how a customer is charged a different price than the one they accepted, or how a later rate change leaks into an offer that was still in date.

How do you build a policy quoting backend with Encore?

Declare the database, the documents bucket, the notices topic, the expiry job and any third-party rating secrets in the service code. When the app deploys to your own AWS or GCP account, Encore provisions the database, the bucket, the topic and the job, and 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