Skip to main content

Payment Platform Data Model

Last Updated: 2026-12-01 Status: Complete

A payment platform data model has two halves: an organizational half (who is allowed to take and receive money) and a financial half (what happened to the money). This page gives you both for a PayFac: the tenant hierarchy, principals, bank accounts, pricing assignment, the payment-side records, money and currency fields, multi-tenancy, and history. You will leave with an ER diagram, PostgreSQL DDL for the core tables and a NestJS DTO for creating a sub-merchant.

Quick Reference​

DecisionRecommended default
Moneybigint minor units plus ISO 4217 code; never floats
Financial records (captures, refunds, settlements)Immutable rows; corrections are new rows
StatusOne mutable status column plus an append-only status history
Tenant scopingplatform_id (and where relevant sub_merchant_id) on every row, enforced in every query
Bank account numbersToken reference plus last four; raw number only in the vault
Rules that change over timeEffective-dated rows, never in-place edits
DeletionSoft-delete or archive operational entities; never delete financial records
MetadataBounded JSONB, never PAN or PII

How Is the Tenant Hierarchy Modeled?​

A PayFac sells to a platform (typically a SaaS company whose customers need to accept payments). The platform onboards sub-merchants (called connected accounts by some vendors): the legal entities that actually sell goods or services. A sub-merchant can have several locations (stores, sites), and each location can have terminals or devices.

Each level exists because something different is decided there:

LevelWhat attaches hereWhy
PlatformDefault pricing, branding, API credentials, webhook endpoints, revenue shareThe commercial contract is with the platform
Sub-merchantKYC/KYB result, MCC, sub-merchant ID, bank accounts, payout schedule, reserve, risk tier, monitoringThe legal entity is underwritten, funded and held liable
LocationDescriptor suffix, address, tax settings, reporting slicesMerchants report and reconcile per store
TerminalDevice identifier, processor terminal ID, key injection statusCard-present routing and troubleshooting

Reporting rolls up from terminal to platform, settlement and payouts happen at sub-merchant level, pricing resolves from sub-merchant up to platform, and risk limits (volume caps, monitoring thresholds) apply per sub-merchant and also in aggregate per platform. If you flatten the hierarchy (for example, one table of "merchants"), every one of those four needs a workaround later.

Where the MID lives: the PayFac holds the master merchant account with the sponsor bank, and each sub-merchant gets its own identifier under it. Store the acquirer-assigned identifiers on the sub-merchant (or a child table keyed by processor if you use several) and never reuse a sub-merchant ID across entities. The identification rules are on Sub-Merchant Management.

Who Are the Principals and How Do You Store Them?​

Beneficial owners and control persons are people, not attributes of the business. Model a person record and link it to the sub-merchant through a role table, so the same individual can be an owner of one entity and a control person of another, and so each role carries its own ownership percentage.

TableKey fields
personid, legal name, date of birth and government ID as vault references, address, tenant ids
principal_rolesub_merchant_id, person_id, role (beneficial_owner, control_person, signer), ownership_bps, effective_from, effective_to
kyc_checkperson_id or sub_merchant_id, provider, provider_reference, result, checked_at

Store the provider's reference and your normalized result, not a copy of the provider's full report; fetch details from the provider (or your document store) when an examiner asks. Ownership percentages are stored in basis points as integers for the same reason money is. See Beneficial Ownership, and the glossary entries for ultimate beneficial owner and control person. How to protect the identity fields is covered in Sensitive Data Architecture.

How Do You Model Bank Accounts?​

A sub-merchant has many bank accounts, not one. Typical purposes: a payout destination, a debit account for recovering a negative balance, and a separate account for refunds or reserve funding where the sponsor bank requires it.

FieldNotes
purposepayout, debit, or both; constrain with a check
currencyISO 4217; a payout account receives one currency
account_tokenReference to the encrypted or tokenized number in the vault
routing_ref / last4last4 is the only part shown in UI and logs
verification_statusunverified, pending, verified, failed (micro-deposit, instant verification or prenote; your choice of method)
effective_from / effective_toA change is a new row, so you can prove where a past payout went
is_default_payoutAt most one per sub-merchant and currency

Enforce the "one default per currency" rule with a partial unique index (shown in the DDL below), not with application code alone. A bank account change is also a fraud signal (account takeover), so emit an event and consider a payout hold; see Payouts.

How Are Pricing Plans and Users Attached?​

Do not store fee rates on the sub-merchant row. Create a fee_schedule (the plan) and a fee_schedule_assignment with owner_type (platform or sub_merchant), owner_id, fee_schedule_id, effective_from, effective_to. Resolution: the sub-merchant assignment effective on the transaction date wins, otherwise the platform's. Date-based assignment is what lets you answer "what rate applied on 3 March?" after a repricing. The schedule contents and calculation are in the Fee Engine.

Users follow the same split. A user belongs to a platform or to a sub-merchant (a platform admin versus a merchant owner), and role_assignment links it to roles with an explicit scope. Authorization rules are in Access Control.

How Do Payment Intents, Attempts and Captures Relate?​

Model the customer's intent to pay separately from each try at collecting it.

  • Payment intent: what the merchant wants to collect (amount, currency, customer reference, merchant reference). One intent, one business purpose, stable over its life. This is the object the caller's idempotency key is tied to; see Idempotency in Payments.
  • Payment attempt: one try with a payment method (one authorization request). A declined card followed by a retry on a second card is two attempts under one intent: after the decline the intent returns to requires_payment_method and the next attempt moves it back to authorizing.
  • Authorization: the issuer's approval for an attempt, with its own identifiers and validity window (see Authorization Types).
  • Capture: a claim on part or all of an authorization. Multiple partial captures are allowed in some scenarios, so captures are a child table, not a column.
  • Refund: a return of funds linked to a capture (or to the intent). Multiple partial refunds are normal.
  • Void: cancels an authorization or a not-yet-cleared capture; see Void vs Reversal vs Refund.
  • Settlement record: a line from a processor settlement file, linked to a capture or refund.
  • Payout: the funding movement to the sub-merchant's bank, linked to the settlement lines it covers.
  • Dispute and evidence: a chargeback case against a capture, with submitted evidence files.

Worked Model: Authorize, Capture Twice, Refund Partially​

An intent for 10,000 minor units (100.00 in a two-decimal currency) is authorized, shipped in two parcels, then one item is refunded.

StepRow createdAmountResulting intent status
1payment_intent10,000initiated
2payment_attempt #1 and authorization10,000authorized
3capture #16,000partially_captured
4capture #24,000captured
5refund #1 against capture #12,500partially_refunded

Totals are derived: captured = sum of captures (10,000), refunded = sum of refunds (2,500), refundable remainder = captured minus refunded. Enforce the invariant per capture, sum(refunds on a capture) <= capture.amount_minor, inside the transaction that inserts a refund, with a row lock on the capture, or two concurrent refunds will both pass a naive check. Give each capture and refund request a request_key (unique per intent or capture) that retries resend, so a retried request cannot capture or refund twice. The intent is in captured after step 4 and the refund is allowed from there. The state names come from Payment State Machines.

Immutable Records, Mutable Status​

Captures, refunds, settlement records and ledger entries are facts: once written, never updated. The thing that changes is the status of the aggregate. Keep status on the intent and write an append-only status_history row for each change (from, to, cause, actor, timestamp). A correction is a new row (a refund, a reversal, an adjustment), never an edit; this is also what makes an audit trail credible (see Audit Trails). The ledger side of the same principle is in Double-Entry Ledger.

Store every identifier you ever receive on the record that receives it: the processor reference and RRN at authorization, the network transaction ID, and the ARN once clearing assigns it. The settlement record then references a capture through the strongest available key, with a nullable capture_id that is filled when matching succeeds (an unmatched line is data, not an error). The keys, their weaknesses and the break taxonomy are in Reconciliation; index each identifier column you match on.

How Do You Store Money and Currency?​

  • Amounts are bigint in minor units, with the ISO 4217 code beside them. Read the exponent from the published list: JPY has zero minor-unit digits and KWD has three, so never hardcode 2.
  • Keep presentment currency (what the cardholder saw) and settlement currency (what you are funded in) as separate field pairs. When they differ, record the FX rate, its source and the timestamp it was fixed at, so a settlement amount can be explained later. Do not recompute historical amounts from today's rate.
  • Use metadata jsonb for merchant-supplied key-value data, with a size and key-count limit enforced at the API and a check constraint. Never accept or log a PAN, security code or personal data there; scan or reject patterns at the edge.
Time-Sensitive

Currency exponents and codes are maintained by the ISO 4217 maintenance agency and change occasionally. Load the list from a reference table that you update, rather than from constants. For scope and storage questions about card data, confirm with your QSA; see PCI DSS requirements and key numbers.

How Do You Enforce Multi-Tenancy?​

Put platform_id on every tenant-owned row (and sub_merchant_id where a sub-merchant owns the record), index it as the leading column of composite indexes, and apply it in every query. Missing tenant scoping is the classic broken object-level authorization bug: an API caller guesses another tenant's payment ID and reads it. Derive the tenant from the authenticated principal, never from a request body. Access Control covers the API side.

PostgreSQL row-level security is a database-side backstop: enable it on tenant tables and set the tenant per transaction.

ALTER TABLE payment_intent ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON payment_intent
USING (platform_id = current_setting('app.platform_id')::uuid);
-- In each request transaction: SELECT set_config('app.platform_id', $1, true);

The one-argument current_setting raises an error when the variable is unset. That is deliberate fail-closed behavior: a code path that forgot to set the tenant fails loudly instead of returning rows. Caveats: table owners and superusers bypass policies unless you use FORCE ROW LEVEL SECURITY, connection pools must set the variable per transaction (the true argument makes it local), and background jobs that span tenants need a separate, audited role.

Core Tables in PostgreSQL​

-- Each parent has UNIQUE (platform_id, id) so children can use a composite FK
-- and cannot reference another tenant's parent row.
CREATE TABLE sub_merchant (
id uuid PRIMARY KEY,
platform_id uuid NOT NULL REFERENCES platform(id),
legal_name text NOT NULL,
mcc char(4) NOT NULL,
status text NOT NULL, -- see state machines
version integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (platform_id, id)
);

CREATE TABLE bank_account (
id uuid PRIMARY KEY,
platform_id uuid NOT NULL,
sub_merchant_id uuid NOT NULL,
purpose text NOT NULL CHECK (purpose IN ('payout','debit','both')),
currency char(3) NOT NULL,
account_token text NOT NULL, -- vault reference, not the number
last4 char(4) NOT NULL,
verification_status text NOT NULL DEFAULT 'unverified',
is_default_payout boolean NOT NULL DEFAULT false,
effective_from timestamptz NOT NULL DEFAULT now(),
effective_to timestamptz,
FOREIGN KEY (platform_id, sub_merchant_id)
REFERENCES sub_merchant (platform_id, id)
);
CREATE UNIQUE INDEX one_default_payout
ON bank_account (sub_merchant_id, currency)
WHERE is_default_payout AND effective_to IS NULL;

CREATE TABLE payment_intent (
id uuid PRIMARY KEY,
platform_id uuid NOT NULL,
sub_merchant_id uuid NOT NULL,
location_id uuid, -- nullable: default location if unused
amount_minor bigint NOT NULL CHECK (amount_minor > 0),
currency char(3) NOT NULL,
status text NOT NULL,
pre_dispute_status text, -- restored when a dispute is won
version integer NOT NULL DEFAULT 0,
idempotency_key text NOT NULL,
request_hash text NOT NULL, -- fingerprint of the create request
metadata jsonb NOT NULL DEFAULT '{}'
CHECK (octet_length(metadata::text) <= 4096),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (platform_id, idempotency_key),
UNIQUE (platform_id, id),
FOREIGN KEY (platform_id, sub_merchant_id)
REFERENCES sub_merchant (platform_id, id)
);

CREATE TABLE capture (
id uuid PRIMARY KEY,
platform_id uuid NOT NULL,
intent_id uuid NOT NULL,
authorization_id uuid NOT NULL,
request_key text NOT NULL, -- per-request key, resent on retry
amount_minor bigint NOT NULL CHECK (amount_minor > 0),
currency char(3) NOT NULL,
network_txn_id text,
arn text,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (intent_id, request_key),
FOREIGN KEY (platform_id, intent_id)
REFERENCES payment_intent (platform_id, id)
);
-- refund mirrors capture: capture_id, request_key, UNIQUE (capture_id, request_key)

CREATE TABLE payment_status_history (
id bigserial PRIMARY KEY,
platform_id uuid NOT NULL,
intent_id uuid NOT NULL,
from_status text NOT NULL,
to_status text NOT NULL,
event text NOT NULL,
actor text NOT NULL,
external_event_id text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX history_dedupe
ON payment_status_history (intent_id, external_event_id)
WHERE external_event_id IS NOT NULL;

The unique constraint on (platform_id, idempotency_key) is the race-condition guard described in the idempotency post, scoped per tenant. Store request_hash (a hash of the canonical request body) and compare it when the key already exists: the same hash returns the stored result, a different hash is a client error, because a reused key must carry the same parameters. The same pattern applies to capture and refund with request_key: a retry resends the same key and the unique constraint turns a duplicate into a lookup rather than a second capture.

How Do You Create a Sub-Merchant in NestJS?​

The DTO validates shape; the bank number never arrives raw. The client tokenizes it at the edge (see Sensitive Data Architecture) and sends the token reference.

export class PrincipalDto {
@IsString() @Length(1, 120) legalName: string;
@IsEnum(PrincipalRole) role: PrincipalRole;
@IsInt() @Min(0) @Max(10000) ownershipBps: number; // basis points
@IsString() identityRef: string; // vault reference for ID data
}

export class BankAccountDto {
@IsString() accountToken: string; // token reference, never the number
@IsString() @Length(4, 4) last4: string;
@IsISO4217CurrencyCode() currency: string;
@IsEnum(BankAccountPurpose) purpose: BankAccountPurpose;
}

export class CreateSubMerchantDto {
@IsString() @Length(1, 200) legalName: string;
@Matches(/^\d{4}$/) mcc: string;

@ValidateNested({ each: true })
@Type(() => PrincipalDto)
@ArrayMinSize(1)
principals: PrincipalDto[];

@ValidateNested({ each: true })
@Type(() => BankAccountDto)
@ArrayMinSize(1)
bankAccounts: BankAccountDto[];
}
// Controller: new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })
// platformId comes from the authenticated principal, not the DTO.

whitelist and forbidNonWhitelisted stop a caller from injecting fields such as status or platformId.

How Do You Handle History, Soft Delete and Archival?​

  • Effective dating is for facts that legitimately change and must be answerable "as of" a date: bank accounts, fee assignments, principal roles, risk tier, payout schedule. Close the old row (effective_to) and insert a new one in one transaction; use an exclusion constraint if overlapping ranges would be a bug.
  • Soft delete (deleted_at or a terminal status) suits operational entities such as locations, terminals and users: they disappear from UI but stay referenced by history.
  • Never delete financial records: payments, captures, refunds, ledger entries, settlements and disputes are referenced by reconciliation, tax and examiners. Retention periods and deletion of personal data are legal questions; take them to your counsel and your sponsor bank agreement, and see Sensitive Data Architecture for separating personal data from financial facts so personal fields can be erased without breaking money records.
  • Archival: move old partitions to cheaper storage after the period your policy sets, keeping them queryable for audit.

References​

Share: