Updated Nov 23, 20266 min read

Build Transaction Velocity Checks for a Payments Backend

How to build velocity checks that decide allow, review or block from recent activity: count and amount rules over sliding windows, a per-account lock so two requests cannot both slip under a limit, a decision log, and a TypeScript version on Postgres.

Illustration for Build Transaction Velocity Checks for a Payments Backend

A payments backend that only validates amounts and balances will accept a stolen card tested a hundred times in a minute, since each request looks fine alone. Velocity checks look at the pattern: how many attempts, how much money and how many distinct cards one account, device or IP produced in a recent window.

The rules are simple to state and easy to get subtly wrong under concurrency. This guide builds them as a Postgres service that returns allow, review or block and keeps a record of why.

What does a velocity rule look like?

A rule is a window, a measure and a threshold, and the code below implements all three. Stripe's Radar rules reference describes the same idea as attributes that are counts over hourly and daily windows, and notes that the payment being evaluated is not included in the count, so a limit of 5 first triggers on the sixth attempt.

RuleWindowMeasureOutcome
Attempt burst1 minuteAttempts per accountBlock above 5
Sustained attempts1 hourAttempts per accountReview above 20
Daily exposure24 hoursSum of amounts per accountReview above 5,000 in major units

Each rule produces a reason string, and the final decision is the strictest outcome among the rules that fired. Keeping the reasons makes a manual review possible, and a decision that cannot be explained cannot be defended to a customer or an auditor.

How do you count without races?

Two requests for the same account that arrive together both read the count before either writes its attempt, and both pass a limit that only one should. A transaction-level advisory lock fixes this. Per the PostgreSQL advisory lock functions, pg_advisory_xact_lock blocks until it can take the lock and releases it automatically when the transaction ends, so checks for one account run in turn and the second sees the first's row.

The lock key is a hash of the account ID, which means two unrelated accounts can occasionally share a lock and wait for each other briefly, and that is an acceptable cost. The count itself is a range scan, so a multicolumn index on (account_id, created_at) keeps it fast, since the equality column comes first and the time range second.

Make the check idempotent as well. The caller sends an attemptId, a unique constraint stores it, and a retry returns the original decision instead of counting the attempt twice.

How does Encore run the velocity service?

Encore is a backend framework with built-in infrastructure, so the rules service is an endpoint and a SQLDatabase in the same service. Per the AWS infrastructure docs, the deploy provisions Postgres on RDS in your own account, and encore run starts Postgres locally for the same code.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

A check endpoint that the payments service calls before it authorizes, with the rules as data in code:

// velocity/velocity.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; const db = new SQLDatabase("velocity", { migrations: "./migrations" }); type Decision = "allow" | "review" | "block"; interface Rule { name: string; windowSeconds: number; maxAttempts?: number; maxAmountCents?: number; outcome: Exclude<Decision, "allow">; } const RULES: Rule[] = [ { name: "attempt_burst", windowSeconds: 60, maxAttempts: 5, outcome: "block" }, { name: "sustained_attempts", windowSeconds: 3600, maxAttempts: 20, outcome: "review" }, { name: "daily_exposure", windowSeconds: 86_400, maxAmountCents: 500_000, outcome: "review" }, ]; const RANK: Record<Decision, number> = { allow: 0, review: 1, block: 2 }; interface CheckRequest { attemptId: string; accountId: string; amountCents: number; } interface CheckResponse { decision: Decision; reasons: string[]; } export const check = api( { expose: false, method: "POST", path: "/velocity/check" }, async (req: CheckRequest): Promise<CheckResponse> => { if (!Number.isInteger(req.amountCents) || req.amountCents <= 0) { throw APIError.invalidArgument("amountCents must be a positive integer"); } const tx = await db.begin(); try { // Checks for one account run one after another until this transaction ends. await tx.exec`SELECT pg_advisory_xact_lock(hashtext(${req.accountId}))`; const prior = await tx.queryRow<{ decision: Decision; reasons: string }>` SELECT decision, reasons FROM attempts WHERE attempt_id = ${req.attemptId}`; if (prior) { await tx.commit(); return { decision: prior.decision, reasons: JSON.parse(prior.reasons) }; } let decision: Decision = "allow"; const reasons: string[] = []; for (const rule of RULES) { // The attempt being checked is not in the table yet, so it is not counted. const w = await tx.queryRow<{ n: number; total: number }>` SELECT count(*)::int AS n, coalesce(sum(amount_cents), 0)::float8 AS total FROM attempts WHERE account_id = ${req.accountId} AND created_at > now() - make_interval(secs => ${rule.windowSeconds})`; const countHit = rule.maxAttempts !== undefined && (w?.n ?? 0) >= rule.maxAttempts; const amountHit = rule.maxAmountCents !== undefined && (w?.total ?? 0) + req.amountCents > rule.maxAmountCents; if (countHit || amountHit) { reasons.push(rule.name); if (RANK[rule.outcome] > RANK[decision]) decision = rule.outcome; } } await tx.exec` INSERT INTO attempts (attempt_id, account_id, amount_cents, decision, reasons) VALUES (${req.attemptId}, ${req.accountId}, ${req.amountCents}, ${decision}, ${JSON.stringify(reasons)})`; await tx.commit(); return { decision, reasons }; } catch (err) { await tx.rollback(); throw err; } }, );
-- velocity/migrations/1_init.up.sql CREATE TABLE attempts ( attempt_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, amount_cents BIGINT NOT NULL CHECK (amount_cents > 0), decision TEXT NOT NULL CHECK (decision IN ('allow', 'review', 'block')), reasons TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX attempts_account_time_idx ON attempts (account_id, created_at);

The endpoint is expose: false, so only the payments service in the same app can call it, as a typed call from ~encore/clients per the API calls docs. The same pattern covers other limits: add a rule with a different window, or a second table keyed on device or IP. Locally, encore run starts Postgres, so the burst rule can be tested by calling the endpoint six times in a row.

To deploy, connect your AWS or GCP account as described in Connect your cloud account and push with git push encore. The attempt history stays in your own account, in a database you can query for audits.

A coding agent that adds a rule changes the RULES list and a migration in one pull request and tests the threshold locally, without touching any cloud setting.

Best fit: Payments and banking teams that want velocity rules in code with an auditable decision log, running against Postgres in their own cloud account.

What should you test before go-live?

Send six attempts for one account within a minute and confirm the sixth is blocked and the reason is recorded. Replay an attemptId and confirm the decision is identical and the count does not move, then run ten concurrent requests for one account and confirm no more than five passed.

Frequently asked questions

What is a velocity check in payments?

A velocity check limits how much activity an account, card, device or IP address can generate in a time window, for example no more than five attempts per minute or 5,000 dollars per day. Hitting a limit leads to a block or to a manual review, depending on the rule.

How do I implement velocity checks without Redis?

Store every attempt in a Postgres table with an index on the account and time, and count the rows inside each window when a new attempt arrives. At moderate volumes this is accurate and gives you the history for audits, and Redis counters become worthwhile when attempts per second reach the thousands.

How do I stop two simultaneous requests from both passing a limit?

Take a transaction-level advisory lock keyed on the account before counting, so concurrent checks for the same account run one after another. The second request then sees the first one's attempt in its count.

How do I deploy a payments rules service to my own cloud without managing infrastructure code?

With Encore you declare the SQLDatabase and the endpoints in the service, and the deploy provisions Postgres in your own AWS or GCP account, with encore run starting Postgres locally. Rules live in code next to the check.

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