How to turn completed deliveries into earnings lines with a dated rate card, post adjustments without rewriting history, close a settlement period exactly once, hold back negative balances and hand payouts to a payment provider safely, on AWS or GCP.

Paying drivers per delivery starts as a multiplication in a spreadsheet and becomes a ledger problem within weeks, once late proof of delivery, a rate change or a disputed drop arrives after a payout has left.
This guide builds the settlement service with a dated rate card, adjustments that never edit history and a weekly close that is safe to rerun.
Most of the correctness comes from two details: INSERT ... ON CONFLICT DO NOTHING, described in the Postgres INSERT reference, which turns a duplicate event into a no-op, and the idempotency key on the payout call, which payment providers such as Stripe document for safely retrying requests without paying twice.
An earnings table holds every line with a nullable settlement_id, and a line belongs to a settlement once that column is set. The settlement is one SQL statement with a common table expression that sums the unsettled lines per driver, inserts a statement for each driver with a positive total and updates the lines it summed, so the sum and the claim see the same snapshot and a line that arrives a moment later waits for the next run. A unique constraint on driver and period makes a rerun of the same day a no-op. Payout requests need a queue, the weekly close needs a scheduler that survives restarts, and the payment provider call needs a secret and a retry policy.
Encore brings infrastructure from code, so the earnings tables, the payout topic and the weekly close 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 records a completed delivery, accepts adjustments, closes the period and requests payouts:
// settlements/settlements.go
package settlements
import (
"context"
"fmt"
"strings"
"time"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("settlements", sqldb.DatabaseConfig{Migrations: "./migrations"})
type PayoutRequested struct {
SettlementID int64 `json:"settlement_id"`
DriverID string `json:"driver_id"`
NetCents int64 `json:"net_cents"`
}
var payouts = pubsub.NewTopic[*PayoutRequested]("payout-requested", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type DeliveryParams struct {
DeliveryID string `json:"delivery_id"`
DriverID string `json:"driver_id"`
Kilometers float64 `json:"kilometers"`
DeliveredAt time.Time `json:"delivered_at"`
}
// RecordDelivery adds one earnings line, priced from the rate card in force on the delivery date.
//
//encore:api public method=POST path=/deliveries/completed
func RecordDelivery(ctx context.Context, p *DeliveryParams) error {
if strings.TrimSpace(p.DeliveryID) == "" || strings.TrimSpace(p.DriverID) == "" || p.Kilometers < 0 {
return &errs.Error{Code: errs.InvalidArgument, Message: "delivery_id, driver_id and a non-negative distance are required"}
}
res, err := db.Exec(ctx, `
INSERT INTO earnings (driver_id, ref, kind, cents, earned_at)
SELECT $2, $1, 'delivery', rc.base_cents + round(rc.per_km_cents * $3::numeric)::bigint, $4
FROM rate_cards rc
WHERE rc.effective_from <= ($4::timestamptz)::date
ORDER BY rc.effective_from DESC LIMIT 1
ON CONFLICT (ref) DO NOTHING`, p.DeliveryID, p.DriverID, p.Kilometers, p.DeliveredAt)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
var exists bool
if err := db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM earnings WHERE ref = $1)`, p.DeliveryID).Scan(&exists); err != nil {
return err
}
if !exists {
return &errs.Error{Code: errs.FailedPrecondition, Message: "no rate card in force on the delivery date"}
}
}
return nil
}
type AdjustParams struct {
Key string `json:"key"`
Cents int64 `json:"cents"`
Reason string `json:"reason"`
}
// Adjust posts a positive or negative line. Settled lines are never edited.
//
//encore:api public method=POST path=/drivers/:id/adjustments
func Adjust(ctx context.Context, id string, p *AdjustParams) error {
if p.Key == "" || p.Cents == 0 {
return &errs.Error{Code: errs.InvalidArgument, Message: "key and a non-zero amount are required"}
}
_, err := db.Exec(ctx, `
INSERT INTO earnings (driver_id, ref, kind, cents, earned_at, note)
VALUES ($1, $2, 'adjustment', $3, now(), $4)
ON CONFLICT (ref) DO NOTHING`, id, "adj-"+p.Key, p.Cents, p.Reason)
return err
}
type Balance struct {
DriverID string `json:"driver_id"`
Cents int64 `json:"cents"`
}
//encore:api public method=GET path=/drivers/:id/balance
func GetBalance(ctx context.Context, id string) (*Balance, error) {
b := Balance{DriverID: id}
err := db.QueryRow(ctx, `
SELECT COALESCE(sum(cents), 0)::bigint FROM earnings
WHERE driver_id = $1 AND settlement_id IS NULL`, id).Scan(&b.Cents)
return &b, err
}
// Settle closes everything earned before today for drivers with a positive total.
//
//encore:api private
func Settle(ctx context.Context) error {
periodEnd := time.Now().UTC().Format("2006-01-02")
_, err := db.Exec(ctx, `
WITH due AS (
SELECT driver_id, sum(cents) AS net, count(*) AS n FROM earnings
WHERE settlement_id IS NULL AND earned_at < $1::date
GROUP BY driver_id HAVING sum(cents) > 0
), made AS (
INSERT INTO settlements (driver_id, period_end, net_cents, line_count)
SELECT driver_id, $1::date, net, n FROM due
ON CONFLICT (driver_id, period_end) DO NOTHING
RETURNING id, driver_id
)
UPDATE earnings e SET settlement_id = made.id
FROM made
WHERE e.driver_id = made.driver_id AND e.settlement_id IS NULL AND e.earned_at < $1::date`, periodEnd)
if err != nil {
return err
}
rows, err := db.Query(ctx, `SELECT id, driver_id, net_cents FROM settlements WHERE status = 'pending'`)
if err != nil {
return err
}
var pending []*PayoutRequested
for rows.Next() {
var r PayoutRequested
if err := rows.Scan(&r.SettlementID, &r.DriverID, &r.NetCents); err != nil {
rows.Close()
return err
}
pending = append(pending, &r)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, r := range pending {
if _, err := payouts.Publish(ctx, r); err != nil {
return err
}
}
return nil
}
var _ = cron.NewJob("weekly-settlement", cron.JobConfig{
Title: "Close the weekly driver settlement",
Schedule: "0 4 * * 1",
Endpoint: Settle,
})
var _ = pubsub.NewSubscription(payouts, "send-payout", pubsub.SubscriptionConfig[*PayoutRequested]{
Handler: func(ctx context.Context, r *PayoutRequested) error {
key := fmt.Sprintf("settlement-%d", r.SettlementID)
// Call the payment provider here with `key` as the idempotency key.
_ = key
_, err := db.Exec(ctx, `
UPDATE settlements SET status = 'paid', paid_at = now()
WHERE id = $1 AND status = 'pending'`, r.SettlementID)
return err
},
RetryPolicy: &pubsub.RetryPolicy{MinBackoff: 10 * time.Second, MaxBackoff: 5 * time.Minute, MaxRetries: 5},
})
-- settlements/migrations/1_create_settlements.up.sql
CREATE TABLE rate_cards (
effective_from DATE PRIMARY KEY,
base_cents BIGINT NOT NULL,
per_km_cents NUMERIC NOT NULL
);
INSERT INTO rate_cards (effective_from, base_cents, per_km_cents) VALUES ('2026-01-01', 400, 55);
CREATE TABLE settlements (
id BIGSERIAL PRIMARY KEY,
driver_id TEXT NOT NULL,
period_end DATE NOT NULL,
net_cents BIGINT NOT NULL CHECK (net_cents > 0),
line_count INT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
paid_at TIMESTAMPTZ,
UNIQUE (driver_id, period_end)
);
CREATE TABLE earnings (
id BIGSERIAL PRIMARY KEY,
driver_id TEXT NOT NULL,
ref TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL,
cents BIGINT NOT NULL,
earned_at TIMESTAMPTZ NOT NULL,
note TEXT,
settlement_id BIGINT REFERENCES settlements (id)
);
CREATE INDEX earnings_unsettled_idx ON earnings (driver_id) WHERE settlement_id IS NULL;
encore run starts Postgres locally and applies the migration, so completing a delivery twice, posting an adjustment and reading the balance can be driven with curl, and the weekly close is tested by calling the Settle endpoint from the local development dashboard because cron jobs do not run locally. The database docs cover migrations, the Pub/Sub docs cover retries and the dead-letter queue, and the cron docs cover schedules, which the Encore platform manages.
To deploy, follow Connect your cloud account and push, and the RDS or Cloud SQL database, the topic and the schedule are created in your account. The payout subscriber is where the provider call goes, with its API key stored as an Encore secret, and an AI coding agent adding a minimum-guarantee rule edits the settlement query and its test in one change that it can run locally first.
Best fit: Logistics and delivery teams that pay drivers per job and want earnings, adjustments and weekly settlements handled in a service that runs in their own AWS or GCP account.
Confirm with finance whether the period closes in UTC or in the depot time zone, since the query above settles everything earned before the current UTC date. Keep tax, benefits and local pay rules in your own logic, because they differ by country and by whether drivers are employees or contractors. Decide who may post adjustments and keep the reason on every line. Reconcile paid settlements against the payment provider's report, and alert on any settlement that stays pending longer than a day.
Store a rate card with an effective date, and when a delivery completes insert one earnings line priced from the card in force on that date, such as a base amount plus an amount per kilometer. Keying the line by delivery identifier makes a retried completion event insert nothing the second time.
Post an adjustment line, positive or negative, against the driver instead of editing a settled line. The adjustment is picked up by the next settlement, and the statement for the closed period stays exactly as it was paid.
Leave the lines unsettled so they roll into the next period instead of creating a payout. The settlement query only creates a statement for drivers whose total is positive, and the negative total keeps accumulating until later deliveries cover it.
Build it with Encore, declaring the database, the payout topic and the weekly cron job in code, and deploy it to your own AWS or GCP account. encore run starts Postgres locally, so the earnings and settlement 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.