How to enforce per-transaction, daily and monthly spend limits and merchant category blocks inside a real-time authorization decision, with atomic counters, idempotent retries and freeze events, built with Encore.

A card program starts with one rule, decline anything over the cardholder's limit, and then grows a daily cap, a monthly cap, blocked merchant categories and a freeze button. Each rule runs inside the authorization decision, where the processor gives you about two seconds to answer.
Two purchases that arrive at the same moment are where limit checks usually fail, so this guide designs the counters first and then builds the decision with Encore.
The processor sends an authorization request with an ID, the amount in minor units, the currency and the merchant category code (MCC). Stripe Issuing's spending controls describe the same shapes: limits per interval, plus allowed and blocked categories. Your decision checks them in a fixed order, cheapest first: card status, per-transaction limit, category rules, then the counters.
The order matters because the counters are the only step that spends the limit. A frozen card or a blocked category should never touch them, and a decline at any step has to leave the counters unchanged.
Reading the current total, adding the new amount in code and writing it back lets two requests read the same total. Put the check inside the write instead. An upsert with a WHERE clause on the update branch only changes the row when the new total fits under the limit, and returns nothing when it does not.
The amount itself must be compared to the limit first, because the insert branch of an upsert has no WHERE. Windows are keyed by the card's local day or month, so the key is computed from the cardholder's time zone rather than the server's.
Processors retry when they do not get an answer, and a retry that increments the counter again would use up the cardholder's limit with no purchase behind it. Insert each authorization ID into a table with a primary key as the first statement of the transaction that updates the counters. A concurrent retry with the same ID waits on that key until the first transaction ends, then finds the stored decision and returns it, and a crash between the counter update and the response rolls back as one unit.
Idempotency keys cover the same pattern for payment APIs, and the double-entry ledger guide covers what happens after the authorization is captured.
Encore is a backend framework with built-in infrastructure, and the authorization service declares its Postgres database and a Pub/Sub topic for decline and freeze events as code. Encore provisions both in your AWS or GCP account. Pave Bank built a bank in 9 months with Encore.

Run in your terminal to get started locally.
-- controls/migrations/1_create_controls.up.sql
CREATE TABLE card_controls (
card_id TEXT PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'active', -- active | frozen
per_txn_cents BIGINT,
daily_cents BIGINT,
monthly_cents BIGINT,
blocked_mccs TEXT[] NOT NULL DEFAULT '{}',
timezone TEXT NOT NULL DEFAULT 'UTC'
);
CREATE TABLE spend_counters (
card_id TEXT NOT NULL,
window_kind TEXT NOT NULL, -- day | month
window_start DATE NOT NULL,
spent_cents BIGINT NOT NULL,
PRIMARY KEY (card_id, window_kind, window_start)
);
CREATE TABLE authorizations (
auth_id TEXT PRIMARY KEY, -- one row per processor authorization
card_id TEXT NOT NULL,
amount_cents BIGINT NOT NULL,
approved BOOLEAN NOT NULL,
reason TEXT NOT NULL,
decided_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// controls/controls.ts
import { api } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic } from "encore.dev/pubsub";
const db = new SQLDatabase("controls", { migrations: "./migrations" });
interface ControlEvent {
cardId: string;
authId: string;
outcome: "declined";
reason: string;
}
const events = new Topic<ControlEvent>("card-control-events", {
deliveryGuarantee: "at-least-once",
});
interface AuthRequest {
authId: string;
cardId: string;
amountCents: number;
mcc: string;
}
interface AuthDecision {
approved: boolean;
reason: string;
}
export const authorize = api(
{ expose: false, method: "POST", path: "/authorize" },
async (req: AuthRequest): Promise<AuthDecision> => {
const tx = await db.begin();
// Claim the authorization ID before anything else. A concurrent retry with
// the same ID waits on this primary key until the transaction ends.
let claimed: { auth_id: string } | null;
try {
claimed = await tx.queryRow<{ auth_id: string }>`
INSERT INTO authorizations (auth_id, card_id, amount_cents, approved, reason)
VALUES (${req.authId}, ${req.cardId}, ${req.amountCents}, false, 'pending')
ON CONFLICT (auth_id) DO NOTHING
RETURNING auth_id`;
} catch (err) {
await tx.rollback();
throw err;
}
if (!claimed) {
// A retry returns the stored decision without touching the counters.
await tx.rollback();
const seen = await db.queryRow<AuthDecision>`
SELECT approved, reason FROM authorizations WHERE auth_id = ${req.authId}`;
if (!seen) throw new Error(`authorization ${req.authId} has no stored decision`);
return seen;
}
let decision: AuthDecision = { approved: true, reason: "ok" };
try {
const card = await tx.queryRow<{
status: string;
per_txn_cents: number | null;
daily_cents: number | null;
monthly_cents: number | null;
blocked_mccs: string[];
timezone: string;
}>`SELECT status, per_txn_cents, daily_cents, monthly_cents, blocked_mccs, timezone
FROM card_controls WHERE card_id = ${req.cardId}`;
if (!card) {
decision = { approved: false, reason: "card_not_found" };
} else if (card.status !== "active") {
decision = { approved: false, reason: "card_frozen" };
} else if (card.per_txn_cents !== null && req.amountCents > card.per_txn_cents) {
decision = { approved: false, reason: "over_per_transaction_limit" };
} else if (card.blocked_mccs.includes(req.mcc)) {
decision = { approved: false, reason: "blocked_category" };
} else if (
(card.daily_cents !== null && req.amountCents > card.daily_cents) ||
(card.monthly_cents !== null && req.amountCents > card.monthly_cents)
) {
decision = { approved: false, reason: "over_period_limit" };
}
if (decision.approved && card) {
// A decline on the second window undoes the first one back to here.
await tx.exec`SAVEPOINT counters`;
const windows = [
{ kind: "day", limit: card.daily_cents, trunc: "day" },
{ kind: "month", limit: card.monthly_cents, trunc: "month" },
];
for (const w of windows) {
if (w.limit === null) continue;
// The WHERE clause makes the limit check part of the write, so two
// concurrent purchases cannot both fit under the same remaining amount.
const row = await tx.queryRow<{ spent_cents: number }>`
INSERT INTO spend_counters (card_id, window_kind, window_start, spent_cents)
VALUES (${req.cardId}, ${w.kind},
date_trunc(${w.trunc}, now() AT TIME ZONE ${card.timezone})::date,
${req.amountCents})
ON CONFLICT (card_id, window_kind, window_start)
DO UPDATE SET spent_cents = spend_counters.spent_cents + ${req.amountCents}
WHERE spend_counters.spent_cents + ${req.amountCents} <= ${w.limit}
RETURNING spent_cents`;
if (!row) {
decision = { approved: false, reason: `over_${w.kind}_limit` };
await tx.exec`ROLLBACK TO SAVEPOINT counters`;
break;
}
}
}
await tx.exec`
UPDATE authorizations SET approved = ${decision.approved}, reason = ${decision.reason}
WHERE auth_id = ${req.authId}`;
await tx.commit();
} catch (err) {
await tx.rollback();
throw err;
}
if (!decision.approved) {
await events.publish({
cardId: req.cardId,
authId: req.authId,
outcome: "declined",
reason: decision.reason,
});
}
return decision;
},
);
export const freeze = api(
{ expose: false, method: "POST", path: "/cards/:cardId/freeze" },
async ({ cardId }: { cardId: string }): Promise<void> => {
await db.exec`UPDATE card_controls SET status = 'frozen' WHERE card_id = ${cardId}`;
},
);
With an encore.service.ts file in controls/, encore run starts a local Postgres, applies the migration and serves the endpoints, so a test can fire two concurrent authorizations and check that only one fits. On deploy, the database runs on RDS or Cloud SQL, the topic on SNS and SQS or GCP Pub/Sub as the AWS and GCP docs describe, and Encore provisions an IAM role for the service.
A coding agent adding a notification consumer for declines subscribes to card-control-events in the same change and runs it locally, without creating a queue or wiring permissions in a separate step.
Best fit: Teams building a card program on top of an issuing processor who want the limit logic, its tests and its infrastructure in one repository.
On AWS the same service needs an RDS instance, an ECS or Lambda deployment for the decision endpoint behind an ALB, an SNS topic with SQS queues for decline consumers and IAM for each piece, all in Terraform. The TypeScript above stays nearly identical. The extra work is the infrastructure definitions and keeping a local Postgres, topic and test setup in step with them.
Keep a counter per card and day, and update it with a single conditional statement that only succeeds when the new total stays under the limit. The authorization approves when the update returns a row and declines when it does not, so two concurrent purchases cannot both squeeze under the limit.
Card networks and issuer processors allow only a short window. Stripe Issuing, for example, expects a response to a real-time authorization webhook within 2 seconds, and a late response falls back to the default decision. Keep the decision to a few indexed database operations in one transaction and publish everything else as an event.
Insert each authorization ID into a table with a unique constraint as the first step of the transaction that updates the counter. A concurrent retry waits on that key until the first transaction ends, then finds the stored decision and returns it without touching the counter again.
With Encore, declare the Postgres database and a Pub/Sub topic for control events next to the authorization handler. Encore provisions them in your AWS or GCP account, and the whole decision path runs locally with encore run.
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.