How to quote and bind mid-term policy changes with a pro rata premium adjustment, guard against stale quotes, keep every version of the terms so a claim can be checked against the day of loss, and run it on AWS or GCP.

A policy system usually starts with issue and renewal, and the first change request shows what is missing: a customer adds a vehicle in March, and a claim in August has to be checked against the terms from the loss date. Updating the row in place loses that history.
This guide builds the endorsement service with quotes, pro rata premium, a version check at bind time and effective-dated terms.
An endorsement adds, removes or changes coverage and can be issued mid-term, which is why the NAIC consumer guide says it can affect the premium, and the pro rata method charges or returns the annual difference in proportion to the days left, as the Genasys glossary illustrates with a worked example. Your rating rules and policy wording decide when pro rata applies, so the formula below is one function to replace.
The policy row holds the current terms and a version number, and an endorsements table holds each requested change with the version it was quoted against. The quote is a single INSERT ... SELECT that computes the delta in SQL and takes an idempotency key, so a client that retries the request gets the same quote back through ON CONFLICT. Binding runs in a transaction that locks the policy row with FOR UPDATE, compares versions, writes the new version and marks the endorsement bound, following the Postgres rules for explicit row locks. You also need a queue to hand the premium adjustment to billing, a scheduler to void quotes that were never bound, and a database that behaves the same on a laptop and in production.
Encore brings infrastructure from code, so the policy tables, the billing topic and the quote cleanup schedule are declared with the endpoints and created in your own AWS or GCP account on deploy. The AWS docs list Fargate, RDS and SNS with SQS, and the GCP docs list Cloud Run, Cloud SQL and Pub/Sub.

Run in your terminal to get started locally.
The service creates a policy, quotes an endorsement, binds it with a version check and answers which terms applied on a date:
// policies/policies.go
package policies
import (
"context"
"encoding/json"
"errors"
"time"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("policies", sqldb.DatabaseConfig{Migrations: "./migrations"})
type EndorsementBound struct {
EndorsementID int64 `json:"endorsement_id"`
PolicyID int64 `json:"policy_id"`
DeltaCents int64 `json:"delta_cents"`
}
var bound = pubsub.NewTopic[*EndorsementBound]("endorsement-bound", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type CreateParams struct {
Holder string `json:"holder"`
EffectiveOn string `json:"effective_on"`
ExpiresOn string `json:"expires_on"`
AnnualPremiumCents int64 `json:"annual_premium_cents"`
}
type CreateResponse struct {
ID int64 `json:"id"`
}
//encore:api public method=POST path=/policies
func Create(ctx context.Context, p *CreateParams) (*CreateResponse, error) {
from, err1 := time.Parse("2006-01-02", p.EffectiveOn)
to, err2 := time.Parse("2006-01-02", p.ExpiresOn)
if p.Holder == "" || err1 != nil || err2 != nil || !to.After(from) || p.AnnualPremiumCents <= 0 {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "holder, a valid term and a positive premium are required"}
}
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, effective_on, expires_on, annual_premium_cents)
VALUES ($1, $2::date, $3::date, $4) RETURNING id`,
p.Holder, p.EffectiveOn, p.ExpiresOn, p.AnnualPremiumCents).Scan(&id)
if err != nil {
return nil, err
}
_, err = tx.Exec(ctx, `
INSERT INTO policy_versions (policy_id, version, effective_on, annual_premium_cents, coverage)
VALUES ($1, 1, $2::date, $3, '{}'::jsonb)`, id, p.EffectiveOn, p.AnnualPremiumCents)
if err != nil {
return nil, err
}
return &CreateResponse{ID: id}, tx.Commit()
}
type QuoteParams struct {
Key string `json:"key"`
EffectiveOn string `json:"effective_on"`
AnnualPremiumCents int64 `json:"annual_premium_cents"`
Coverage map[string]string `json:"coverage"`
}
type Quote struct {
ID int64 `json:"id"`
Status string `json:"status"`
DeltaCents int64 `json:"delta_cents"`
}
// Quote prices a change. The same key returns the same quote.
//
//encore:api public method=POST path=/policies/:id/endorsements
func RequestQuote(ctx context.Context, id int64, p *QuoteParams) (*Quote, error) {
if _, err := time.Parse("2006-01-02", p.EffectiveOn); err != nil || p.Key == "" || p.AnnualPremiumCents <= 0 {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "key, effective_on and a positive premium are required"}
}
coverage, _ := json.Marshal(p.Coverage)
_, err := db.Exec(ctx, `
INSERT INTO endorsements
(policy_id, idempotency_key, base_version, effective_on, new_annual_premium_cents, premium_delta_cents, coverage)
SELECT p.id, $2, p.version, $3::date, $4::bigint,
round(($4::bigint - p.annual_premium_cents)::numeric
* (p.expires_on - $3::date) / (p.expires_on - p.effective_on))::bigint,
$5::jsonb
FROM policies p
WHERE p.id = $1 AND p.status = 'active'
AND $3::date >= p.effective_on AND $3::date < p.expires_on
ON CONFLICT (policy_id, idempotency_key) DO NOTHING`,
id, p.Key, p.EffectiveOn, p.AnnualPremiumCents, string(coverage))
if err != nil {
return nil, err
}
var q Quote
err = db.QueryRow(ctx, `
SELECT id, status, premium_delta_cents FROM endorsements
WHERE policy_id = $1 AND idempotency_key = $2`, id, p.Key).Scan(&q.ID, &q.Status, &q.DeltaCents)
if errors.Is(err, sqldb.ErrNoRows) {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "policy is not active on that date"}
}
if err != nil {
return nil, err
}
return &q, nil
}
// Bind applies a quote once. Calling it again republishes the event for billing.
//
//encore:api public method=POST path=/endorsements/:id/bind
func Bind(ctx context.Context, id int64) (*Quote, error) {
tx, err := db.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
var (
policyID, delta, premium int64
version, base int
status string
effective time.Time
coverage string
)
err = tx.QueryRow(ctx, `
SELECT e.policy_id, p.version, e.base_version, e.status, e.premium_delta_cents,
e.new_annual_premium_cents, e.effective_on, e.coverage::text
FROM endorsements e JOIN policies p ON p.id = e.policy_id
WHERE e.id = $1 FOR UPDATE OF e, p`, id).
Scan(&policyID, &version, &base, &status, &delta, &premium, &effective, &coverage)
if errors.Is(err, sqldb.ErrNoRows) {
return nil, &errs.Error{Code: errs.NotFound, Message: "endorsement not found"}
}
if err != nil {
return nil, err
}
if status == "bound" {
_, err = bound.Publish(ctx, &EndorsementBound{EndorsementID: id, PolicyID: policyID, DeltaCents: delta})
return &Quote{ID: id, Status: status, DeltaCents: delta}, err
}
if status != "quoted" {
return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "quote is " + status}
}
if base != version {
return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "policy changed since this quote, request a new one"}
}
if _, err = tx.Exec(ctx, `
INSERT INTO policy_versions (policy_id, version, effective_on, annual_premium_cents, coverage)
VALUES ($1, $2, $3, $4, $5::jsonb)`, policyID, version+1, effective, premium, coverage); err != nil {
return nil, err
}
if _, err = tx.Exec(ctx, `
UPDATE policies SET version = $2, annual_premium_cents = $3 WHERE id = $1`,
policyID, version+1, premium); err != nil {
return nil, err
}
if _, err = tx.Exec(ctx, `
UPDATE endorsements SET status = 'bound', bound_at = now() WHERE id = $1`, id); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
_, err = bound.Publish(ctx, &EndorsementBound{EndorsementID: id, PolicyID: policyID, DeltaCents: delta})
return &Quote{ID: id, Status: "bound", DeltaCents: delta}, err
}
type Terms struct {
Version int `json:"version"`
EffectiveOn string `json:"effective_on"`
AnnualPremiumCents int64 `json:"annual_premium_cents"`
}
// TermsOn returns the terms in force on a date, such as a date of loss.
//
//encore:api public method=GET path=/policies/:id/terms/:date
func TermsOn(ctx context.Context, id int64, date string) (*Terms, error) {
var t Terms
err := db.QueryRow(ctx, `
SELECT version, effective_on::text, annual_premium_cents FROM policy_versions
WHERE policy_id = $1 AND effective_on <= $2::date
ORDER BY effective_on DESC, version DESC LIMIT 1`, id, date).
Scan(&t.Version, &t.EffectiveOn, &t.AnnualPremiumCents)
if errors.Is(err, sqldb.ErrNoRows) {
return nil, &errs.Error{Code: errs.NotFound, Message: "no terms in force on that date"}
}
if err != nil {
return nil, err
}
return &t, nil
}
var _ = pubsub.NewSubscription(bound, "post-adjustment", pubsub.SubscriptionConfig[*EndorsementBound]{
Handler: func(ctx context.Context, e *EndorsementBound) error {
// One row per endorsement, so a redelivery cannot post the adjustment twice.
_, err := db.Exec(ctx, `
INSERT INTO premium_adjustments (endorsement_id, policy_id, delta_cents)
VALUES ($1, $2, $3) ON CONFLICT (endorsement_id) DO NOTHING`, e.EndorsementID, e.PolicyID, e.DeltaCents)
return err
},
RetryPolicy: &pubsub.RetryPolicy{MinBackoff: 10 * time.Second, MaxBackoff: 5 * time.Minute, MaxRetries: 5},
})
//encore:api private
func VoidStaleQuotes(ctx context.Context) error {
_, err := db.Exec(ctx, `
UPDATE endorsements SET status = 'void'
WHERE status = 'quoted' AND created_at < now() - interval '7 days'`)
return err
}
var _ = cron.NewJob("void-stale-quotes", cron.JobConfig{
Title: "Void endorsement quotes older than 7 days",
Schedule: "0 3 * * *",
Endpoint: VoidStaleQuotes,
})
-- policies/migrations/1_create_policies.up.sql
CREATE TABLE policies (
id BIGSERIAL PRIMARY KEY,
holder TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
effective_on DATE NOT NULL,
expires_on DATE NOT NULL,
annual_premium_cents BIGINT NOT NULL CHECK (annual_premium_cents > 0),
version INT NOT NULL DEFAULT 1,
CHECK (expires_on > effective_on)
);
CREATE TABLE policy_versions (
policy_id BIGINT NOT NULL REFERENCES policies (id),
version INT NOT NULL,
effective_on DATE NOT NULL,
annual_premium_cents BIGINT NOT NULL,
coverage JSONB NOT NULL,
PRIMARY KEY (policy_id, version)
);
CREATE TABLE endorsements (
id BIGSERIAL PRIMARY KEY,
policy_id BIGINT NOT NULL REFERENCES policies (id),
idempotency_key TEXT NOT NULL,
base_version INT NOT NULL,
effective_on DATE NOT NULL,
new_annual_premium_cents BIGINT NOT NULL,
premium_delta_cents BIGINT NOT NULL,
coverage JSONB NOT NULL,
status TEXT NOT NULL DEFAULT 'quoted',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
bound_at TIMESTAMPTZ,
UNIQUE (policy_id, idempotency_key)
);
CREATE TABLE premium_adjustments (
endorsement_id BIGINT PRIMARY KEY REFERENCES endorsements (id),
policy_id BIGINT NOT NULL,
delta_cents BIGINT NOT NULL,
posted_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
encore run starts Postgres locally and applies the migration, so creating a policy, requesting a quote twice with the same key and binding it can be driven with curl, and the cleanup is tested by calling its endpoint from the local development dashboard because cron jobs do not run locally. 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 RDS or Cloud SQL database, the topic and the schedule are created in your account. The billing subscriber is where the adjustment reaches your billing system, and an AI coding agent adding a second change type, such as a driver removal that carries no premium, edits the quote query and the coverage payload in one change that it can run locally first.
Best fit: Insurance engineering teams that need quotes, binds and effective-dated policy terms handled in a service that runs in their own AWS or GCP account.
Replace the pro rata expression with your rating engine wherever a change needs more than a proportional difference, and keep the formula in the quote so the delta is stored with the endorsement that produced it. Decide how a back-dated endorsement that falls before an already-bound one is ordered, since TermsOn picks the latest effective date and then the highest version. Add an authorization check for who may bind, and write an audit row for every bind and void. Cancellations at the insured's request may use a short-rate rule instead of pro rata, and the policy wording and your regulator decide which applies.
An endorsement, also called a rider, is an amendment to an existing policy that adds, removes or changes coverage, and it can be issued at purchase, mid-term or at renewal, as the [NAIC explains](https://content.naic.org/article/consumer-insight-what-insurance-endorsement-or-rider). A backend records it as a new version of the policy terms with an effective date.
With the pro rata method, the difference between the new and the old annual premium is multiplied by the days left in the term and divided by the days in the term. A positive result is an additional premium and a negative one is a return premium.
Store the policy version on each quote and, when binding, lock the policy row and compare that version with the current one. A quote made against an older version is rejected, and the client requests a new quote against the current terms.
Build it with Encore, declaring the database, the billing topic and the quote cleanup cron job in code, and deploy it to your own AWS or GCP account. encore run starts Postgres locally, so the quote, bind and version queries can be tested before deploying.
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.