Capital allocation dashboard open on a desk in a DeFi protocol operations setting.
Protocols

Database Schema Design for Lightning Payment Data

A technical guide for payment processors and analytics teams on modeling Lightning-specific entities—channels, HTLCs, invoices, routing events—in a relational or time-series database. Focuses on indexing strategies for efficient querying of payment status, aggregating routing revenue, and joining Lightning data with internal user IDs.
introduction
BEYOND THE GENERAL LEDGER

Why a Purpose-Built Lightning Data Model Matters

Standard accounting schemas fail to capture the lifecycle of a Lightning payment, creating blind spots in reconciliation, revenue analysis, and compliance.

A Lightning Network payment is not a simple debit-credit event. It is a composite state machine spanning invoice generation, multi-path HTLC negotiation, potential retries, and eventual settlement or failure. Payment processors and exchanges that attempt to force Lightning data into a generic double-entry ledger inevitably lose the causal chain linking a user's intent to a specific routing outcome. This makes it impossible to answer critical operational questions: Why did a payment fail? What was the effective fee rate for a specific corridor? Which channels are net revenue contributors after accounting for rebalancing costs?

A purpose-built data model treats core Lightning entities—channels, HTLCs, invoices, and routing events—as first-class objects with their own lifecycles. This allows for efficient indexing on payment_hash for atomic status queries, time-series aggregation of routing revenue by channel ID, and reliable joins between internal user IDs and Lightning payment attempts. Crucially, it separates the intent of a payment (the invoice) from its execution (the HTLC set), enabling precise reconciliation even when a single invoice is settled via multiple partial payments or when a keysend payment arrives without a pre-existing invoice record.

For teams building high-throughput payment systems, the schema design directly impacts the reliability of automated rebalancing logic and the accuracy of financial reporting. A schema that cannot distinguish between a routing fee earned and a rebalancing cost paid will silently corrupt profitability analysis. Chainscore Labs reviews data model designs to ensure they capture the full state machine of Lightning payments, enabling operators to build robust reconciliation pipelines, accurate revenue dashboards, and compliant audit trails that reflect the protocol's actual behavior, not a simplified abstraction of it.

LIGHTNING PAYMENT DATA MODEL

Core Entities and Their Relationships

Key entities that must be modeled in a relational or time-series database to support payment processing, routing revenue aggregation, and compliance reconciliation for a Lightning-integrated business.

EntityCore AttributesOperational DependencyIndexing and Query Strategy

Channels

Channel point, SCID, node IDs, capacity, local/remote balance, commitment fee, state flags (active, closing, closed)

Node operators, liquidity providers, treasury teams

Index on SCID and node pubkeys for fast lookup; join with on-chain UTXO table for fee reconciliation

HTLCs

Channel ID, HTLC ID, amount, expiry, payment hash, state (offered, accepted, settled, failed), forwarding fee

Payment processors, routing node operators, compliance teams

Index on payment_hash for invoice correlation; time-series partition on expiry for stuck-payment alerting

Invoices

Payment hash, payment preimage, amount (msat), description, expiry, state (open, settled, canceled), BOLT 11/12 raw string

Wallet developers, payment processors, accounting teams

Primary index on payment_hash; secondary on user_id and creation timestamp for user-facing payment history

Routing Events

Incoming/outgoing channel IDs, HTLC ID, amount, fee earned, timestamp, success/failure flag

Routing node operators, finance teams, analytics engineers

Index on timestamp and node pubkeys for revenue aggregation; join with channel table to map fees to specific channel partners

Payments (Outgoing)

Payment hash, total amount, fee limit, parts (MPP), status (in-flight, succeeded, failed), retry count

Wallet developers, payment processors, customer support teams

Index on payment_hash and user_id; use status field for monitoring in-flight payment health and retry budgets

On-chain Transactions

Txid, amount, fee rate, confirmation count, label (channel_open, channel_close, splice), block height

Treasury teams, node operators, compliance officers

Index on txid and label; join with channel table to calculate total cost of channel lifecycle management

User/Account Mapping

Internal user ID, node pubkey, invoice/payment references, channel IDs, custody flag

Custodians, exchanges, compliance teams

Index on user_id; enforce referential integrity to link all Lightning activity to internal identity and risk profiles

technical-context
DATA MODELING FOR LIGHTNING PAYMENT PROCESSORS

Schema Architecture and Key Design Decisions

Designing a relational schema that accurately captures the lifecycle of Lightning-specific entities while enabling efficient joins with internal business data.

Modeling Lightning Network payment data in a relational database requires a departure from standard on-chain accounting schemas. The core challenge is that a single logical payment can be composed of multiple Multi-Path Payment (MPP) shards, each represented by a distinct Hash Time-Locked Contract (HTLC) that may be resolved across several channels. A robust schema must treat the invoice, the payment attempt, and the individual HTLCs as separate, joinable entities to allow for atomic reconciliation. This design is critical for payment processors and exchanges that need to map asynchronous Lightning events to internal user IDs, order IDs, or compliance cases without losing the cryptographic proof of payment.

The schema must also handle the dual lifecycle of channels and their underlying Unspent Transaction Outputs (UTXOs). A channels table should track the dynamic state, including the channel_point, short_channel_id, and capacity, while a separate onchain_transactions table records the funding, splicing, and force-close events that anchor these channels to the Bitcoin base layer. Indexing strategies should prioritize the payment_hash for HTLC lookups and the short_channel_id for routing revenue aggregation. For time-series analysis of forwarding events, a dedicated hypertable or partitioned table is often necessary to maintain query performance at scale, as a single routing node can generate millions of forwarding records daily.

A key design decision involves the handling of spontaneous payments via Keysend, which lack a traditional invoice. The schema must accommodate a payment_preimage as the primary proof-of-payment without a corresponding invoice record, while still allowing the payment to be linked to a known user or purpose through custom TLV (Type-Length-Value) data. This pattern is essential for integrating Lightning Address protocol payments or automated service tips into a compliant audit trail. Teams building these systems should review their data model against edge cases like stuck payments, where an HTLC is held for hours before being resolved or failed, to ensure the schema correctly reflects the unsettled liability during that window.

Chainscore Labs provides data model review for payment processors and exchanges, ensuring that the schema design correctly handles the asynchronous and multi-part nature of Lightning payments. We assess indexing strategies for high-throughput environments, validate the integrity of joins between Lightning data and internal business systems, and help teams design reconciliation logic that can withstand the operational complexities of channel closures and routing failures.

DATABASE DESIGN FOR LIGHTNING PAYMENT DATA

Schema Impact by Team

Payment Processor Schema Impact

Payment processors must model the full lifecycle of a payment, from invoice generation to settlement finality. The core schema must join internal user IDs with Lightning-specific entities.

Critical Entities:

  • invoices: Store BOLT 11 and BOLT 12 invoices with payment_hash, amount_msat, description, expiry, and state (OPEN, SETTLED, CANCELED). Index payment_hash for fast lookup during HTLC settlement.
  • htlcs: Record each incoming HTLC with channel_id, amount_msat, cltv_expiry, and state. Join to invoices on payment_hash to handle MPP reassembly.
  • payments: Track outgoing payments with payment_hash, status, fee_msat, and parts (JSON array for MPP).

Indexing Strategy:

  • Composite index on (user_id, created_at) for user-facing payment history.
  • Partial index on state = 'PENDING' for monitoring stuck payments.
  • Time-series table for routing events if revenue aggregation is required.

Action: Review your schema for MPP support. Ensure payment_hash is the universal join key across invoices, HTLCs, and payments. Chainscore Labs can audit your data model for edge cases like zero-amount invoices and spontaneous payments.

implementation-impact
DATA MODELING FOR LIGHTNING PAYMENTS

Implementation Patterns and Query Workflows

Practical database schemas and indexing strategies for modeling Lightning-specific entities—channels, HTLCs, invoices, and routing events—to enable efficient payment reconciliation, revenue aggregation, and operational monitoring.

01

Core Entity-Relationship Model for Lightning Data

Design a normalized schema that cleanly separates on-chain channel funding events from off-chain HTLC lifecycle states. Map each channel open to its funding transaction, then track the sequence of commitment transactions and the HTLCs they contain. Use a composite key of channel_id and commitment_index to uniquely identify each state update. This model allows precise reconstruction of channel balances over time and is the foundation for detecting force-close scenarios and calculating accurate routing revenue.

02

Indexing HTLCs for High-Throughput Payment Reconciliation

HTLCs are the atomic unit of a Lightning payment and must be queryable by payment hash, forwarding node, and timelock expiry. Create a dedicated htlc_events table with a composite index on (payment_hash, event_timestamp). This enables an exchange or payment processor to join an incoming invoice settlement notification with its corresponding outgoing HTLC forward in sub-millisecond time, which is critical for real-time order-book matching and user balance updates during high volatility.

03

Aggregating Routing Revenue with Time-Series Bucketing

Routing fees are collected in sub-satoshi increments across thousands of micro-transactions. Implement a materialized view or a time-series database (e.g., TimescaleDB) that buckets forwarding_history events by hour. Pre-calculate the sum of fee_msat grouped by incoming_channel_id and outgoing_channel_id. This pattern avoids expensive full-table scans on the raw events table and provides a performant backend for dashboards that display per-channel profitability and aggregate node revenue for financial reporting.

04

Joining Internal User IDs with Pseudonymous Node Data

A critical integration challenge is linking a user's internal account ID to an ephemeral Lightning payment. Create a mapping table that associates a user_id with a payment_hash at the moment of invoice generation. When the htlc_events table records a settlement, a simple join provides the user context. This design avoids embedding business logic into the core protocol data tables and maintains a clean separation of concerns, which is essential for compliance and customer support workflows.

05

Schema for BOLT 12 Offers and Static Identifiers

BOLT 12 replaces single-use invoices with persistent offer_ids. Extend your schema to include an offers table keyed by this ID, with a one-to-many relationship to invoice_requests and final invoices. Index the payer_key to enable querying all payment attempts against a specific offer. This structure is necessary for implementing recurring payment logic and for building a verifiable audit trail that spans the entire lifecycle from an initial static offer to a settled payment.

LIGHTNING PAYMENT DATA MODELING

Data Integrity and Operational Risks

Evaluates the operational risks and data integrity challenges introduced by modeling Lightning-specific entities in relational or time-series databases for payment processors and analytics teams.

AreaWhat changesWho is affectedAction

Invoice State Reconciliation

BOLT 11 invoices lack a global state machine; a payment can be settled on-chain via force-close while the database marks it as 'in-flight'.

Payment processors, exchange engineering teams

Implement a reconciliation daemon that cross-references channel close transactions on-chain to resolve stuck database states.

HTLC Lifecycle Tracking

An HTLC's state transitions (accepted, settled, failed, canceled) are ephemeral and streamed via the node's API; missing an event leads to a permanent data gap.

Infrastructure teams, data engineers

Design an event-sourcing pipeline that consumes every HTLC event from the node's streaming interface before acknowledging settlement to the user.

Routing Fee Accounting

Routing fees are earned on forwarded HTLCs, not on the initiating payment. Incorrectly joining payment data with forwarding events can misattribute revenue.

Finance teams, analytics engineers

Model routing events in a separate fact table keyed on incoming/outgoing channel IDs and HTLC IDs, not the payment hash, to ensure accurate fee aggregation.

Channel Point Instability

Channel points (funding txid:vout) are static identifiers. Splicing introduces dynamic channel points, breaking foreign-key relationships in schemas that treat them as immutable.

Wallet developers, database architects

Introduce a durable internal channel identifier and map it to the current channel point. Plan a migration for splicing support before it is widely deployed.

MPP Partial Payment Atomicity

A multi-path payment is settled as multiple independent HTLCs. A database that marks the payment complete after the first part arrives will report false successes.

Wallet developers, payment processors

Model MPPs with a parent payment record and child HTLC records. The parent's status must only transition to 'settled' when the sum of child amounts meets the invoice value.

Keysend Audit Trail Gaps

Spontaneous payments lack a standard invoice, removing the typical proof-of-payment. A schema relying on invoice IDs as the primary key will be unable to record these flows.

Compliance teams, security engineers

Create a separate transaction type for keysend payments, using the payment preimage as the proof-of-payment and linking it to a sender node ID for compliance records.

Force-Close Data Recovery

During a force-close, the final channel state is resolved on-chain. The database must correctly link the on-chain sweep transaction to the prior off-chain channel state for accurate balance reporting.

Custodians, node operators

Design a process that, upon detecting a force-close, queries the node for the final channel state before the closing transaction confirms and writes a final, immutable snapshot to the database.

LIGHTNING PAYMENT DATA MODEL READINESS

Schema Rollout and Migration Checklist

A structured checklist for teams preparing to deploy or migrate a relational or time-series database schema for Lightning Network payment data. Each item identifies a critical validation step, explains its operational importance, and specifies the artifact or signal that confirms readiness.

What to check: Verify that the schema accurately models the lifecycle of core Lightning entities: channels (funding, commitment transactions, state), HTLCs (offered, received, resolved), invoices (BOLT 11 and BOLT 12), and routing events (forwarding, failures).

Why it matters: A mismatch between the schema and the protocol's state machine leads to irreconcilable payment records. For example, failing to model the channel_id change during a splice or the payment_hash to payment_preimage resolution for an HTLC will break audit trails and financial reporting.

Readiness signal: An entity-relationship diagram (ERD) exists that maps each database table to a specific BOLT specification section and documents the state transitions for each entity.

Chains We Build On

Looking to build on a specific blockchain?

We build smart contracts, DeFi applications, wallets, tokenization platforms, and blockchain infrastructure across the major ecosystems teams choose today. That includes Ethereum, Arbitrum, Optimism, Polygon, Avalanche, Solana, Sui, Aptos, Hedera, Stellar, and NEAR, with support for additional EVM and non-EVM networks based on your product requirements.

EVM ecosystems

  • Ethereum logo
    Ethereum
  • Arbitrum logo
    Arbitrum
  • Optimism logo
    Optimism
  • Polygon logo
    Polygon
  • Avalanche logo
    Avalanche
  • Cronos logo
    Cronos

Non-EVM ecosystems

  • Solana logo
    Solana
  • Sui logo
    Sui
  • Aptos logo
    Aptos
  • Hedera logo
    Hedera
  • Stellar logo
    Stellar
  • NEAR logo
    NEAR

Additional ecosystems

  • Polkadot logo
    Polkadot
  • Cosmos logo
    Cosmos
  • TON logo
    TON
  • Cardano logo
    Cardano
  • Algorand logo
    Algorand
  • Tempo logo
    Tempo

Also available for Base, appchains, custom EVM networks, and cross-chain product architecture.

SCHEMA DESIGN FAQ

Frequently Asked Questions

Common questions from payment processors and analytics teams modeling Lightning-specific entities in relational and time-series databases.

Use the short_channel_id (scid) as the natural primary key once the channel is confirmed. The scid is a compact, globally unique identifier composed of the funding transaction's block height, transaction index, and output index.

Why it matters: The scid is the canonical identifier used in gossip messages, routing, and HTLC settlement. It enables direct joins with network graph data and routing events.

Implementation guidance:

  • For unconfirmed channels, use a temporary internal UUID until the funding transaction is mined and the scid is known.
  • Store the funding_txid and funding_output_index as separate indexed columns to reconstruct the scid and to join with on-chain transaction data.
  • Be aware that splicing (dynamic channel resizing) changes the funding outpoint. Your schema must handle a channel's lifecycle across multiple funding outpoints, potentially using a channel_id from the peer protocol as a stable identifier.
Trusted by Industry Leaders

Delivering blockchain solutions for 5+ years.

We have partnered with 50+ leading DeFi protocols, NFT ecosystems, and fintech innovators to build secure, scalable, and capital-efficient blockchain products.

Selected Partners & Clients

ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
ChainVote logo
Reax logo
Sokail logo
Swapsicle logo
SyntheX logo
Tekika logo
Telos logo
Zexe logo
“I've been working with Chainscore Labs for last 3+ years, they've consistently delivered with strong ownership across multiple projects. The team is reliable and detail-oriented.”
L
Lee Erswell
CEO, Telos Foundation
how to get started

How to get started?

If you're looking for blockchain integration, ChainScore Labs has 5+ years of experience helping teams build and integrate exchanges, wallets, smart contracts, tokenization solutions, and protocol-connected products, we can help you choose the right path, integrate securely, and get to production faster. Our team consists of experienced blockchain developers and architects who can help you with your blockchain integration needs.

01

Exploration & Strategy

Define your product goals and choose the right blockchain architecture for your use case.

02

Architecture & Design

Design the smart contracts, tokenomics, and security parameters of your system.

03

Development & Integration

Build and integrate with wallets, oracles, and front-end dApps for a seamless experience.

04

Security & Launch

Comprehensive audits followed by a risk-managed mainnet deployment to protect your users.

Start a build

Need a blockchain engineering team?

Send the project context and we will respond with next steps, scope questions, and a practical path to delivery.