Off-Chain Data With PostgreSQL - Patterns for dApps

Schema design, idempotent ingestion, reorg handling and query patterns for storing dApp data in PostgreSQL alongside your smart contracts.

In this guide
  1. What belongs off-chain
  2. Model on-chain values correctly
  3. Make ingestion idempotent
  4. Handle chain reorganizations
  5. Store user and application data safely
  6. Query and scale patterns
  7. Operational checklist
  8. FAQ
  9. Sources

Most dApps need a regular database next to their contracts. The chain stays the source of truth for ownership and balances, while PostgreSQL holds a queryable copy of on-chain events plus the data that never belonged on-chain: profiles, drafts, search indexes, notifications. The patterns that make this reliable are exact numeric types, idempotent writes keyed by chain position, and a clean way to undo blocks after a reorg.

This guide targets PostgreSQL 19, released in November 2026. Unless noted, the SQL also runs on older supported versions.

What belongs off-chain

Contract storage is expensive and public, and it can only be read efficiently by key. A database is cheap, private by default and can be queried any way you like. A workable split:

Data Where it lives Reason
Balances, ownership, protocol rules Contract Must be verifiable and enforced by consensus
Event history, aggregates, leaderboards PostgreSQL (derived from chain) Needs filtering, sorting, joins
User profiles, settings, drafts PostgreSQL (off-chain only) Private, mutable, no need for consensus
Large files and media Object or content-addressed storage, with a pointer in PostgreSQL Too large for either

Keep two categories apart in your head and in your schema:

  • Derived data can be rebuilt from the chain at any time. Losing it is an inconvenience.
  • Authoritative off-chain data exists nowhere else. It needs backups, access control and the same care as any other application database.

Deciding this boundary is a core part of system design, and it is one of the responsibilities described in the blockchain architect role.

Model on-chain values correctly

EVM types do not map onto the PostgreSQL types web developers reach for first.

  • uint256 amounts exceed bigint, which tops out near 9.2 × 10^18. A token balance with 18 decimals passes that quickly. Use numeric(78,0): a uint256 has at most 78 decimal digits, and numeric arithmetic is exact. The documentation notes that numeric is slower than integer types, so keep bigint for values that genuinely fit, such as block numbers and log indexes.
  • Addresses and hashes are raw bytes. Store them as bytea (20 and 32 bytes) with a length check. This is more compact than hex text and avoids the classic bug where the same address appears in two different letter cases and fails an equality comparison.
  • Timestamps from blocks are Unix seconds. Convert them to timestamptz on the way in so date functions work.
CREATE TABLE blocks (
    number     bigint PRIMARY KEY,
    hash       bytea NOT NULL CHECK (octet_length(hash) = 32),
    parent     bytea NOT NULL CHECK (octet_length(parent) = 32),
    mined_at   timestamptz NOT NULL
);

CREATE TABLE transfers (
    block_number bigint NOT NULL REFERENCES blocks (number) ON DELETE CASCADE,
    log_index    integer NOT NULL,
    tx_hash      bytea NOT NULL CHECK (octet_length(tx_hash) = 32),
    token        bytea NOT NULL CHECK (octet_length(token) = 20),
    sender       bytea NOT NULL CHECK (octet_length(sender) = 20),
    recipient    bytea NOT NULL CHECK (octet_length(recipient) = 20),
    amount       numeric(78,0) NOT NULL CHECK (amount >= 0),
    PRIMARY KEY (block_number, log_index)
);

CREATE INDEX transfers_recipient_idx ON transfers (recipient, block_number DESC);
CREATE INDEX transfers_sender_idx    ON transfers (sender, block_number DESC);

To write and read these from application code, convert at the boundary:

-- hex string in, hex string out
INSERT INTO blocks (number, hash, parent, mined_at)
VALUES ($1, decode($2, 'hex'), decode($3, 'hex'), to_timestamp($4));

SELECT '0x' || encode(sender, 'hex') AS sender, amount::text AS amount
FROM transfers
WHERE recipient = decode($1, 'hex');

Pass hex without the 0x prefix to decode. Return amounts as text: JavaScript's number cannot hold them, and most drivers hand numeric back as a string for exactly this reason. Convert to BigInt in the application.

Make ingestion idempotent

An ingestion worker will crash, restart and reprocess blocks. Design so that processing the same block twice produces the same rows.

The natural key for an event log on a single chain is (block_number, log_index). For multi-chain apps, add chain_id as the first key column. With that primary key in place, re-inserts become harmless:

INSERT INTO transfers
    (block_number, log_index, tx_hash, token, sender, recipient, amount)
VALUES ($1, $2, decode($3, 'hex'), decode($4, 'hex'),
        decode($5, 'hex'), decode($6, 'hex'), $7)
ON CONFLICT (block_number, log_index) DO NOTHING;

Track progress in a cursor table, and advance it in the same transaction as the data it describes:

CREATE TABLE sync_cursor (
    stream       text PRIMARY KEY,
    last_block   bigint NOT NULL
);

BEGIN;
-- insert the block row, then its events ...
UPDATE sync_cursor SET last_block = $1 WHERE stream = 'transfers';
COMMIT;

Because the cursor and the rows commit together, a crash can never leave you with a block marked done but only half its events stored.

PostgreSQL 19 adds ON CONFLICT ... DO SELECT, which returns the existing row through RETURNING when an insert conflicts. That makes "get or create" lookups, such as assigning an internal ID to a token address, a single statement. Plain DO NOTHING returns only rows that were actually inserted.

Handle chain reorganizations

Recent blocks can be replaced. If your database keeps rows from a block that is no longer part of the canonical chain, users see transfers that never happened.

Two common strategies:

  1. Wait for finality. Only ingest blocks old enough that the chain treats them as final. Simple, but the data lags.
  2. Ingest the head and roll back when needed. Store each block's hash and parent hash. When a new block's parent does not match the stored hash at the previous height, walk back until the hashes agree, delete everything above that point, and re-ingest.
Blocks 100 and 101 are shared. Stored blocks 102 and 103 belong to a replaced branch and are deleted; the canonical blocks 102, 103 and 104 are ingested again from block 101, the last height where hashes agree.
Walk back to the last block whose hash still matches, delete everything above it, then ingest again.

The schema above makes the rollback one statement, because every event row references its block with ON DELETE CASCADE:

BEGIN;
DELETE FROM blocks WHERE number > $1;          -- $1 = last common ancestor
UPDATE sync_cursor SET last_block = $1 WHERE stream = 'transfers';
COMMIT;

This only works cleanly for append-only event tables. Aggregates such as running balances are harder: you either recompute them from events after a rollback, or store them per block so they are removed along with it. A reasonable default is to keep raw events as the stored truth and compute aggregates in queries or in views that you refresh.

How deep reorgs go, and when a block counts as final, differs between networks and especially between rollups; see Layer 2 explained for developers. If you would rather not write this logic at all, the frameworks compared in indexing blockchain data handle it for you, and several of them write into PostgreSQL.

Store user and application data safely

Authoritative off-chain data typically hangs off a wallet address.

CREATE TABLE profiles (
    address      bytea PRIMARY KEY CHECK (octet_length(address) = 20),
    display_name text CHECK (char_length(display_name) <= 50),
    settings     jsonb NOT NULL DEFAULT '{}',
    updated_at   timestamptz NOT NULL DEFAULT now()
);

Rules that prevent the usual mistakes:

  • Authenticate writes with a signature. A client claiming to be an address proves nothing. Have the user sign a server-issued, single-use challenge with their wallet, verify the signature on the server, then issue a normal session. Our wallet integration guide shows the signing side.
  • Never put secrets or personal data on-chain to "save a table". On-chain data is public and cannot be deleted.
  • Use jsonb for genuinely schemaless content, such as token metadata fetched from external URLs, and regular columns for anything you filter or join on.
  • Treat fetched metadata as untrusted input. Validate size and shape before storing, and escape it on output.

If you need surrogate keys that sort by creation time, PostgreSQL 18 and later include a built-in uuidv7() function.

Query and scale patterns

Index for the questions the UI asks. "Latest activity for this address" is served by the (recipient, block_number DESC) index above.

Paginate by key, not by offset. Event tables grow without bound, and large offsets force the server to walk and discard rows.

SELECT block_number, log_index, amount::text AS amount
FROM transfers
WHERE recipient = decode($1, 'hex')
  AND (block_number, log_index) < ($2, $3)   -- cursor from the previous page
ORDER BY block_number DESC, log_index DESC
LIMIT 50;

Partition very large event tables by block range. Declarative partitioning lets you drop or detach old ranges cheaply. Two details from the documentation matter here: a primary key on a partitioned table must include the partition key, and range bounds are inclusive at the lower end and exclusive at the upper end.

CREATE TABLE logs (
    block_number bigint NOT NULL,
    log_index    integer NOT NULL,
    payload      jsonb NOT NULL,
    PRIMARY KEY (block_number, log_index)
) PARTITION BY RANGE (block_number);

CREATE TABLE logs_p0 PARTITION OF logs
    FOR VALUES FROM (0) TO (10000000);

Push updates with LISTEN/NOTIFY, carefully. Calling pg_notify inside the ingestion transaction tells connected listeners that new data has arrived, and the notification is only sent if the transaction commits. Payloads must stay under 8,000 bytes in the default configuration, and a listener that is disconnected at that moment receives nothing. Send just a block number, and have clients catch up from the cursor when they reconnect.

Feeding other systems. Logical decoding turns the write-ahead log into a stream of row changes that tools can consume to update caches or search indexes. Each consumer reads from a replication slot. An abandoned slot forces the server to retain write-ahead log files, so drop slots you no longer use.

For table bloat after large rollbacks, PostgreSQL 19 introduces REPACK, which can rebuild a table without blocking reads and writes when run with CONCURRENTLY.

Operational checklist

  • Wrap each block's writes and the cursor update in one transaction.
  • Make every insert idempotent with a chain-position key.
  • Store block hashes so reorgs can be detected rather than assumed away.
  • Keep derived tables rebuildable: script the full backfill and test it.
  • Back up authoritative off-chain tables and rehearse a restore.
  • Run a periodic reconciliation job that compares a sample of database values against direct contract reads.
  • Never let the database decide who owns an asset. If the contract and the database disagree, the contract is right.

A project that shows these points end to end fits well among our blockchain portfolio project ideas.

FAQ

Why not store everything on-chain?

Cost, privacy and queryability. Contract storage is paid for by every write, visible to everyone and cannot answer questions like "show the last 50 transfers for this address" without scanning logs. A database handles all three.

Should addresses be stored as text or bytea?

bytea with a length check is the safer default: it is compact and has exactly one representation per address. If you choose text for readability, normalize to lowercase on every write and enforce it with a CHECK constraint.

Which PostgreSQL version should a new project use?

Start on the current major version, 19. If your hosting provider only offers 18, you lose ON CONFLICT DO SELECT and REPACK but nothing else in this guide. The schema and ingestion patterns also run on earlier supported releases; only uuidv7() needs 18 or later.

Sources

About the author

Alessandro Moretti is a crypto analyst and blockchain strategist who writes and maintains the guides on BlockDev Path. Every factual claim is checked against the primary sources listed above. Spotted an error? Tell us and we will correct it. See our editorial policy.