Self-host

The same product on your Postgres: one container, no cluster, no queue, no meter.

You need Docker, the hardware and the CLI: bun add -g @secondlayer/cli.

Configure

$git clone https://github.com/ryanwaits/secondlayer
$cd secondlayer/docker/oss
$cp .env.example .env
$secondlayer init --network mainnet
$cat .env.local >> .env

Start

$docker compose pull
$docker compose up -d
$curl http://127.0.0.1:3800/health
StepWhat it does
POSTGRES_PASSWORDSet it in .env after copying
initGenerates the instance token and signing keys; appending them puts everything compose reads in one .env
pullFetches the published images; without it compose reuses any older copy on the box
/health never answersdocker compose logs secondlayer says why, most often a floor

Use these docs on your box

Point SECONDLAYER_API_URL at your own API.

$export SECONDLAYER_API_URL=http://127.0.0.1:3800
$export INSTANCE_TOKEN=… # from .env.local
$secondlayer subgraphs deploy ./my-subgraph.ts
CaseCredential
Reads on a loopback bindNone. A header with an unknown or empty key is ignored, so the same curl lines work unchanged
Writes over curl, any read past loopbackAuthorization: Bearer $INSTANCE_TOKEN
CLI, SDK, MCPSend INSTANCE_TOKEN for you on any URL that is not the hosted API; MCP needs it in the client config's env, not just your shell
SECONDLAYER_API_KEYLeave it for the hosted account: credits and the Contract state plan's state_writes fetch read it, so setting it to the instance token breaks them. With it set and no INSTANCE_TOKEN, tools use the hosted API unless the URL is set
POSTGRES_PORT, INDEXER_PORTKeep on loopback

Fill it with history

A new box holds only what your node sends from now on. Restore history from the archive, free and with no account.

$export DATABASE_URL=postgres://secondlayer:<POSTGRES_PASSWORD>@127.0.0.1:5432/secondlayer
$secondlayer bootstrap --against https://archive.secondlayer.tools/latest.json
~/secondlayer
$secondlayer bootstrap --against <archive>
coverage genesis → 8,745,422
signature verified
sync from genesis ~19.4 days (estimate)
restore from archive ~2.3 hours
~/secondlayerexit 0
$secondlayer verify raw --against https://archive.secondlayer.tools/latest.json
✓ Local data matches the archive across 183 ranges.
reference signature verified

Stop it

The index, chainstate and keys survive. Never add -v.

$docker compose down

Support is community: github.com/ryanwaits/secondlayer.

Profiles

Set them in .env.

.envsh
$COMPOSE_PROFILES=full-node
ProfileWhat runs
defaultpostgres + secondlayer (API, ingest, decoder, subgraph, webhooks)
full-node+ bundled Stacks node and bitcoind
bitcoin+ runes, the Runes indexer (needs a Bitcoin node with txindex=1)
NODE_MODEYou bringAlso set
external (default)Your Stacks node
stacksYour Stacks node, same as external
fullNothing: both nodes run in the boxBITCOIN_RPC_PASSWORD, the full-node profile

No bundled Stacks-only mode: it needs Bitcoin data.

Pin a version

docker compose up runs latest; pin a commit instead.

.envsh
$SECONDLAYER_VERSION=975e0b9
FactDetail
Imagesghcr.io/ryanwaits/secondlayer-runtime and secondlayer-bitcoin, tagged by short commit
docker compose up -d --buildBuilds your checkout instead

Connect your node

With NODE_MODE=external, this Config.toml entry sends every block: secondlayer observer --mode signer-shared --endpoint 10.0.0.5:3700 prints it.

Config.tomltoml
[[events_observer]]
endpoint = "10.0.0.5:3700"
events_keys = ["*"]
timeout_ms = 500
disable_retries = true
Fieldindexersigner-sharedEffect
endpointhost:porthost:portWhere the node posts blocks. No scheme.
events_keys["*"]["*"]Every standard event. Unknown keys stop a stock node from starting.
timeout_ms2000500How long the node waits on each delivery.
disable_retriesfalsetruefalse retries until delivered, holding up the node meanwhile.
Node on another hostValueWhy
INDEXER_PORT in .env10.0.0.5:3700The default 127.0.0.1:3700 is unreachable off-box
STACKS_NODE_RPC_URL in .envhttp://<node-ip>:20443Polled for the tip when pushes stop
Firewall3700 open to the node's IP onlyThe observer port takes unauthenticated posts

Beside a signer, use signer-shared. The tradeoff: a missed block stays a gap until secondlayer repair fetches it from the archive, free.

Config

Secrets come from secondlayer init; unknown keys fail before ingest.

KeyDefaultNotes
NETWORKmainnetmainnet, testnet, devnet
DATABASE_URLcomposeInjected; one Postgres
NODE_MODEexternalexternal, stacks, full
DATA_DIR/dataHandler + runtime files
API_PORT127.0.0.1:3800Publish spec for the API port
INDEXER_PORT127.0.0.1:3700Publish spec for the observer port
API_PUBLISH_ADDRcomposeInjected from the same API_PORT value the port is published with

Instance token

init writes INSTANCE_TOKEN to .env.local: not the account key from Keys and Billing.

SurfaceCredentialBehavior
/v1 on 127.0.0.1noneyour Postgres, no meter
/v1 past loopbackINSTANCE_TOKENsame header on Index, Streams, subgraphs
Writes (/api/subgraphs, /api/webhooks, /api/node)INSTANCE_TOKENloopback included
# Local read: no key
$curl "http://127.0.0.1:3800/v1/index/events?limit=5"
# Write: instance token, from 127.0.0.1 too
$curl -X POST http://127.0.0.1:3800/api/subgraphs/my-balances/reindex \
-H "Authorization: Bearer $INSTANCE_TOKEN"

Loopback is the publish spec (API_PUBLISH_ADDR), not the caller's address.

API_PORTEffect
127.0.0.1:3800 (default)/v1 reads stay keyless
0.0.0.0:3800Every /v1 request carries the token
EitherWrites take the token. The container binds 0.0.0.0 so the published port reaches it, and an instance that binds past loopback with no token refuses to start

What differs on your box

AreaOn your box
MeteringNone. Your Postgres, no meter, no rate limit
Subgraph sourcesAny. Hosted takes event filters, contract_call and contract_deploy
Typed ORM schemassecondlayer codegen subgraph needs direct Postgres, so it is self-host only
Handler RPC callsSet STACKS_NODE_RPC_URL on the subgraph processor, pointing at the node you already run
History below your bootstrap floorA free archive backfill
Webhook limitsAny max_retries and timeout_ms, no rate limits, egress as your network allows
Proof routesWitness, burn and Bitcoin-header routes answer 503 PROOFS_UNAVAILABLE until PROOF_SIDECAR_URL points at a proof sidecar. The Bitcoin transaction route reads the bundled bitcoind (full-node profile, txindex=1) or the node at BITCOIN_RPC_URL, and answers 502 PROOF_SOURCE_ERROR when it can't reach one
Bitcoin output spends/v1/bitcoin/outspend reads the same node and needs Bitcoin Core 24 or later. It answers 503 BITCOIN_UNAVAILABLE until BITCOIN_RPC_URL is set, and 502 BITCOIN_SOURCE_ERROR when it can't read the node
Error reportsNo /v1/feedback. Error bodies link to a GitHub issue instead
Consumers on another boxDeploy a Consumer

Verify and repair

Archive owns flags and exit codes.

$secondlayer verify all --against <manifest>
$secondlayer repair --against <manifest> # plan
$secondlayer repair --against <manifest> --apply

Archive trust root

One key checks every manifest. The tradeoff: rotating it means a CLI release.

OrderKey source
1--public-key
2ARCHIVE_SIGNING_PUBLIC_KEY in your env
3The key compiled into the CLI release
FactDetail
Applies tobootstrap, verify and repair
initWrites the resolved key into .env.local, so the instance verifies with no path to any Secondlayer host
http:// key sourcesNever consulted
latest.json pointerMust verify against the same key before its snapshot is followed
Pin a different archiveReplace ARCHIVE_SIGNING_PUBLIC_KEY in .env; a value you set there survives init re-runs

Running other teams' subgraphs

Handlers run with the instance's trust: give each team its own stack.

Per teamSetting
DatabaseIts own Postgres and its own network
Containersapi and subgraph-processor under gVisor (runtime: runsc), as a non-root user
LimitsRead-only root filesystem, bounded memory, CPU and process count
NetworkinggVisor can't reach Docker's embedded DNS: a static address for Postgres and a plain resolv.conf

docker/workload/tenant.compose.yml is the working shape.

Not in the box

MissingInstead
Multi-tenant catalogNone
A managed stackHosted subgraphs and webhooks run on api.secondlayer.tools with an account key
Archive publisherA separate image
Pay-per-call meteringThe x402 rail was removed

Mainnet full history is about 500 GB.

SetupRAMDisk
App services, external node, mainnet4 GB600 GB
App services, external node, testnet/devnet4 GB80 GB
Bundled node, mainnet (floor)96 GB2.5 TB
Bundled node, mainnet (recommended)128 GB3 TB NVMe
Sizing factDetail
GrowthAbout 3 GB per 100k blocks for core datasets, 6 GB with a broad decoder set; averages over history much denser at the tip
Bundled nodeStacks chainstate alone measures 1.3 TB, and bitcoind is additional
Postgresmax_connections of 50 or more
POSTGRES_SHARED_BUFFERSCompose sets 1 GB; for a full-chain sync give it about 25% of RAM, since at the stock 128 MB inserts wait on index reads
RunesAdds RAM and disk: Runes

Floors enforced at start

The runtime refuses to boot below the RAM, disk and max_connections floors.

$SECONDLAYER_ALLOW_UNDERSIZED=true
FactDetail
DiskTotal size, not free
Unmeasurable dimensionSkipped
SECONDLAYER_ALLOW_UNDERSIZEDDowngrades the refusal to a warning, so an undersized box can come back after an upgrade

Back up first, then move to a newer release.

Backup

One bundle: the index plus the keys, encrypted under your passphrase.

$secondlayer backup --out ./backups/$(date +%F)
$secondlayer restore --from ./backups/2026-08-16 # dry run
$secondlayer restore --from ./backups/2026-08-16 --apply
Flag or envEffect
--passphrase or SECONDLAYER_BACKUP_PASSPHRASEThe passphrase the keys are encrypted under
--no-secretsWrites a data-only bundle
--force (restore)Lets a restore write over a database that already holds chain data
Restore guaranteeDetail
Key mismatchRefuses before writing if the instance's secrets key isn't the one the data was encrypted with
All or nothingpg_restore runs in one transaction and stops on the first error, so a full disk leaves the target as it was. The tradeoff is no parallel restore
Scope checkAfter the load, the canonical block range is compared with the manifest; a dump that stops short exits 1
DigestStreamed, so a multi-gigabyte bundle hashes without loading into memory
Bundle contentsDetail
KeysINSTANCE_TOKEN, SECONDLAYER_SECRETS_KEY, STREAMS_SIGNING_PRIVATE_KEY
After restoreConfirm with verify all
StorageApart from Postgres backups: the archive rebuilds the index, not the keys

Upgrade

Move from commit X to Y. Read the changelog after X first.

$curl -s "$SECONDLAYER_API_URL/health"
$docker compose images
$secondlayer --version
KeepWhy
postgres_data volumechain, subgraph tables, webhook rows
subgraphs_data volumecompiled handlers
secondlayer_data volumethe generated secrets key, when SECONDLAYER_SECRETS_KEY is unset
SECONDLAYER_SECRETS_KEYdecrypts webhook signing secrets in Postgres
INSTANCE_TOKENcallers; required at boot
STREAMS_SIGNING_PRIVATE_KEY, SECONDLAYER_WEBHOOK_SIGNING_PRIVATE_KEYplatform signature on deliveries
POSTGRES_PASSWORDthe volume already uses it
NeverWhy
docker compose down -vDeletes postgres_data
Losing SECONDLAYER_SECRETS_KEYEvery signing secret becomes unreadable: rotate each webhook
Mainnet dumpTakes hours: snapshot the volume if you can
CLI versionA separate npm version from the images
secondlayer init --forceMints a new secrets key, leaving webhook secrets unreadable
Bootstrap as an upgradeIt refuses a database that already has blocks
$git fetch && git checkout <Y>
# .env: SECONDLAYER_VERSION=<Y>
$docker compose pull
$docker compose up -d --remove-orphans

Migrations run at boot, forward-only.

$curl "$SECONDLAYER_API_URL/health"
$secondlayer verify all --against <manifest>

To roll back, pin X again: the schema stays migrated.

Edit on GitHub

Copy Prompt

Pick what you're building, then copy this prompt into your agent.

Product
Set up Secondlayer Index in this project. It reads Stacks chain data, decoded, from block 1.

1. Install `@secondlayer/sdk` with the project's package manager. If a release-age policy blocks the install, stop and ask me instead of changing it.
2. Ask me for a Secondlayer API key (`sk-sl_...`, from https://www.secondlayer.tools/signin) and put it in `.env` as `SECONDLAYER_API_KEY`. Never commit it. If I self-host, use `INSTANCE_TOKEN` and my instance URL instead. Until I give you one, read with a free docs key: `curl -X POST https://api.secondlayer.tools/api/public/docs-key` returns `{ key }`, read-only for Streams and Index, good for 24 hours and 100,000 rows. Keep it out of git too.
3. Add a note to `AGENTS.md`, creating it if needed: before using Secondlayer, follow the secondlayer skill if it's installed, and read https://www.secondlayer.tools/llms.txt. Before writing code, read https://www.secondlayer.tools/docs/index.md. Any docs page opens as Markdown when you add `.md` to its URL.
4. If you support skills, run: `bunx skills add ryanwaits/secondlayer --skill secondlayer -y`