Nov 18, 20269 min read

Transaction Monitoring Backend: Rules, Alerts and Case Review

Build the backend behind AML and fraud transaction monitoring: event ingestion, velocity and threshold rules, idempotent alerts, analyst case queues, SAR deadlines and an audit trail, all in your own AWS or GCP account.

Illustration for Transaction Monitoring Backend: Rules, Alerts and Case Review

Every fintech that moves money needs transaction monitoring, and most start with a cron job that runs SQL over yesterday's transactions. It works until volume grows, rules multiply, the same alert fires three times for one payment, and an examiner asks when an alert was raised, who reviewed it and why it was closed. At that point the job is a system: a stream of transactions in, rules over time windows, alerts that are deduplicated, cases with owners and deadlines, and an audit trail you can export.

This guide builds that backend: the ingestion path, rule evaluation with velocity counters, idempotent alerts, analyst case review, and SAR deadline tracking. The rules and thresholds below are illustrative; your compliance team owns the actual scenarios and their tuning.

Transaction monitoring at a glance

PartJobStorage
IngestionReceive every settled transaction onceQueue or topic
RulesThresholds, velocity, structuring, new counterpartiesCode plus config
CountersCounts and sums per account per windowRedis
AlertsOne per transaction per rule, with score and reasonPostgres
CasesGrouped alerts, assignee, status, due datePostgres
Audit logEvery decision with actor and reasonAppend-only Postgres table

Design decisions that matter

Asynchronous by default. AML rules look at patterns across hours or days, and an alert leads to review by a person, so monitoring consumes a stream of settled transactions instead of sitting in the authorization path. Card fraud checks that must block a payment belong in a separate synchronous service with a strict latency budget.

At-least-once delivery, idempotent alerts. Queues redeliver. A unique constraint on (transaction_id, rule) makes a redelivered message produce the same alert instead of a duplicate, and analysts never see two copies of one hit.

Counters with fixed windows. A velocity rule such as "more than 10 outbound transfers in an hour" needs a counter per account per window. Keying the counter by account and hour bucket keeps it to one atomic increment, and the key expires on its own.

Deadlines from detection. Under 31 CFR 1020.320, a US bank must file a SAR no later than 30 calendar days after initial detection of facts that may be a basis for filing, may take up to 30 more days if no suspect has been identified, and must keep supporting records for five years from the date of filing. Store detected_at on the case and compute the due date from it, so overdue cases show up in a query, not a spreadsheet. FinCEN's filing information covers the BSA E-Filing system the SAR itself goes through.

Audit everything. Alert creation, assignment, status changes and the closing rationale go into an append-only table with the actor and timestamp. A trigger rejects updates and deletes so existing rows cannot be rewritten. Retention and purge are an operational decision outside this schema. That table is what you hand to an auditor, and it is what an internal review reads when a case is questioned.

How do you build this with Encore?

Encore

Encore is a backend framework with built-in infrastructure. You declare the Pub/Sub topic, the cache cluster and the database in Go, and Encore provisions them in your own AWS or GCP account: SNS and SQS or GCP Pub/Sub, ElastiCache or Memorystore for Redis, and RDS or Cloud SQL. Transaction data stays in infrastructure you control, which is useful when a security review asks where the data lives. Pave Bank, a licensed bank on the customers page, runs on Encore in its own cloud.

Schema

-- monitoring/migrations/1_init.up.sql CREATE TABLE alerts ( id BIGSERIAL PRIMARY KEY, transaction_id TEXT NOT NULL, account_id TEXT NOT NULL, rule TEXT NOT NULL, reason TEXT NOT NULL, amount_cents BIGINT NOT NULL, case_id BIGINT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (transaction_id, rule) ); CREATE TABLE cases ( id BIGSERIAL PRIMARY KEY, account_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'open', -- open, escalated, closed_no_action, sar_filed assignee TEXT, detected_at TIMESTAMPTZ NOT NULL, sar_due_at TIMESTAMPTZ NOT NULL, closed_note TEXT ); CREATE UNIQUE INDEX one_open_case_per_account ON cases (account_id) WHERE status IN ('open', 'escalated'); CREATE TABLE audit_log ( id BIGSERIAL PRIMARY KEY, case_id BIGINT, actor TEXT NOT NULL, action TEXT NOT NULL, detail JSONB NOT NULL DEFAULT '{}', created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE FUNCTION audit_log_append_only() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'audit_log is append-only'; END; $$; CREATE TRIGGER audit_log_append_only BEFORE UPDATE OR DELETE ON audit_log FOR EACH ROW EXECUTE PROCEDURE audit_log_append_only();

Consume transactions and run rules

The ledger service publishes each settled transaction. The monitoring service subscribes, updates the velocity counter, evaluates rules, and records alerts in one database transaction.

package monitoring import ( "context" "fmt" "time" "encore.dev/pubsub" "encore.dev/storage/cache" "encore.dev/storage/sqldb" ) type Transaction struct { ID string `json:"id"` AccountID string `json:"account_id"` Direction string `json:"direction"` // "in" or "out" AmountCents int64 `json:"amount_cents"` Country string `json:"country"` SettledAt time.Time `json:"settled_at"` } var Settled = pubsub.NewTopic[*Transaction]("transaction-settled", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) var db = sqldb.NewDatabase("monitoring", sqldb.DatabaseConfig{Migrations: "./migrations"}) var counters = cache.NewCluster("monitoring", cache.ClusterConfig{ EvictionPolicy: cache.NoEviction, }) type window struct { Account string Hour string } var outboundPerHour = cache.NewSetKeyspace[window, string](counters, cache.KeyspaceConfig{ KeyPattern: "velocity/:Account/:Hour", DefaultExpiry: cache.ExpireIn(2 * time.Hour), }) type hit struct{ rule, reason string } var _ = pubsub.NewSubscription(Settled, "monitor", pubsub.SubscriptionConfig[*Transaction]{ Handler: evaluate, AckDeadline: 60 * time.Second, RetryPolicy: &pubsub.RetryPolicy{MaxRetries: 10}, }) func evaluate(ctx context.Context, t *Transaction) error { var hits []hit if t.AmountCents >= 1_000_000 { hits = append(hits, hit{"large_amount", "single transaction of $10,000 or more"}) } if t.Direction == "out" { key := window{t.AccountID, t.SettledAt.UTC().Format("2006010215")} if _, err := outboundPerHour.Add(ctx, key, t.ID); err != nil { return err } n, err := outboundPerHour.Len(ctx, key) if err != nil { return err } if n > 10 { hits = append(hits, hit{"outbound_velocity", fmt.Sprintf("%d outbound transfers in one hour", n)}) } } if len(hits) == 0 { return nil } return recordAlerts(ctx, t, hits) }

Velocity counters are a Redis set of transaction IDs for the account and hour, so a redelivered message is added once and cannot inflate the count. The alert itself lives in Postgres, where the unique constraint makes redelivery harmless. Structuring rules, such as several cash deposits slightly under a reporting threshold within a day, follow the same pattern with a sum keyspace instead of a count.

Alerts, cases and the audit trail

Each alert attaches to the account's open case or opens a new one, with the SAR due date computed from detection.

func recordAlerts(ctx context.Context, t *Transaction, hits []hit) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var caseID int64 err = tx.QueryRow(ctx, ` INSERT INTO cases (account_id, detected_at, sar_due_at) VALUES ($1, now(), now() + interval '30 days') ON CONFLICT (account_id) WHERE status IN ('open', 'escalated') DO UPDATE SET account_id = EXCLUDED.account_id RETURNING id`, t.AccountID).Scan(&caseID) if err != nil { return err } for _, h := range hits { res, err := tx.Exec(ctx, ` INSERT INTO alerts (transaction_id, account_id, rule, reason, amount_cents, case_id) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (transaction_id, rule) DO NOTHING`, t.ID, t.AccountID, h.rule, h.reason, t.AmountCents, caseID) if err != nil { return err } if res.RowsAffected() == 1 { if _, err := tx.Exec(ctx, ` INSERT INTO audit_log (case_id, actor, action, detail) VALUES ($1, 'system', 'alert_created', jsonb_build_object('rule', $2::text, 'transaction_id', $3::text))`, caseID, h.rule, t.ID); err != nil { return err } } } return tx.Commit() }

The upsert on the partial unique index returns the open case if one exists, so concurrent alerts for one account land in the same case. The due date is set when the case opens and does not move when later alerts join it, which matches a deadline that runs from initial detection.

Analyst endpoints

Analysts work cases through typed APIs behind your auth handler. Closing a case requires a note, an analyst role, and that the case is already assigned to the caller. Claiming an unassigned case is a separate step, also limited to the analyst role. Each of those updates writes to the audit log in the same transaction.

package monitoring import ( "context" "encore.dev/beta/auth" "encore.dev/beta/errs" ) type Session struct { Role string } type CloseParams struct { Outcome string `json:"outcome"` // "closed_no_action" or "sar_filed" Note string `json:"note"` } //encore:api auth method=POST path=/cases/:id/claim func ClaimCase(ctx context.Context, id int64) error { s, _ := auth.Data().(*Session) if s == nil || s.Role != "analyst" { return &errs.Error{Code: errs.PermissionDenied, Message: "analyst role required"} } analyst, _ := auth.UserID() tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() res, err := tx.Exec(ctx, ` UPDATE cases SET assignee = $2 WHERE id = $1 AND status IN ('open', 'escalated') AND assignee IS NULL`, id, string(analyst)) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.FailedPrecondition, Message: "case is not open"} } if _, err := tx.Exec(ctx, ` INSERT INTO audit_log (case_id, actor, action, detail) VALUES ($1, $2, 'case_claimed', '{}'::jsonb)`, id, string(analyst)); err != nil { return err } return tx.Commit() } //encore:api auth method=POST path=/cases/:id/close func CloseCase(ctx context.Context, id int64, p *CloseParams) error { if p.Note == "" || (p.Outcome != "closed_no_action" && p.Outcome != "sar_filed") { return &errs.Error{Code: errs.InvalidArgument, Message: "outcome and note are required"} } s, _ := auth.Data().(*Session) if s == nil || s.Role != "analyst" { return &errs.Error{Code: errs.PermissionDenied, Message: "analyst role required"} } analyst, _ := auth.UserID() tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() res, err := tx.Exec(ctx, ` UPDATE cases SET status = $2, closed_note = $3 WHERE id = $1 AND status IN ('open', 'escalated') AND assignee = $4`, id, p.Outcome, p.Note, string(analyst)) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.FailedPrecondition, Message: "case is not open"} } if _, err := tx.Exec(ctx, ` INSERT INTO audit_log (case_id, actor, action, detail) VALUES ($1, $2, 'case_closed', jsonb_build_object('outcome', $3::text, 'note', $4::text))`, id, string(analyst), p.Outcome, p.Note); err != nil { return err } return tx.Commit() }

A cron job can query sar_due_at < now() + interval '5 days' each morning and notify the compliance lead about cases close to their deadline. Encore's tracing shows each message's path from publish through rule evaluation to the alert insert, which helps when someone asks why a transaction did or did not alert.

Rules are plain Go, so a coding agent can add a scenario as a pull request with tests, and the topic, cache and database it touches are declared in that same code, reviewed before anything changes in your cloud.

Best fit: fintech teams that want transaction monitoring in their own AWS or GCP account, with rules in code and a case trail they can export for examiners.

Buy, build or both

Vendor platforms bring tuned scenarios, model-based scoring and regulator-familiar case tools, and many teams buy one once volume and product lines grow. Building fits when your products are new enough that vendor scenarios miss them, when you want monitoring data in your own account, or when you need a first system live before a vendor contract is signed. Many teams do both: an in-house stream and case store, with a vendor model scoring alerts.

Frequently asked questions

What is a transaction monitoring system?

It is the backend that screens every payment, transfer and card transaction against rules or models, raises alerts on suspicious patterns such as structuring, rapid movement of funds or unusual velocity, and gives compliance analysts a queue to review alerts, open cases and decide whether to file a Suspicious Activity Report.

Should transaction monitoring run synchronously or asynchronously?

Both, for different jobs. Fraud checks that must block a payment run synchronously in the authorization path with a tight latency budget. AML monitoring usually runs asynchronously on a stream of settled transactions, since it looks at patterns over hours or days and an alert leads to human review, not an instant decline.

How long does a bank have to file a SAR?

Under 31 CFR 1020.320, a US bank must file a SAR no later than 30 calendar days after initial detection of facts that may be a basis for filing, with up to 30 more days if no suspect has been identified, and must keep supporting records for five years from the date of filing. Other institution types and countries have their own rules, so confirm with your compliance team.

Can I build transaction monitoring with Encore?

Yes. Encore gives you Pub/Sub topics for the transaction stream, a Redis cache for velocity counters, Postgres for alerts, cases and audit records, and typed APIs for the analyst tools, all declared in Go code and provisioned in your own AWS or GCP account.

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