Skip to main content

Migrate an existing gateway

Spanway can take over from an existing gateway deployment that uses the same config.yaml layout and the same virtual key format, without reissuing keys. spanwayctl migrate gateway-db copies the old gateway's Postgres database into a Spanway database and keeps the stored key hashes byte for byte. Both gateways hash a virtual key the same way (plain SHA-256 of the sk-... value), so clients keep sending the keys they already have. spanwayctl migrate gateway-config translates the config file and the env file.

The database copy opens the old database in a read-only session and never writes to it, so the old gateway can keep serving traffic until you switch over. If the session turns out to be writable, for example because a connection pooler dropped the read-only option, the command stops before reading anything. Point --source-db-url at the database directly in that case.

A real-world scenario​

A company has run a gateway for a year. Two hundred applications hold virtual keys from it, and a dozen teams have budgets and spend history in its database. The platform team wants to move to Spanway over a weekend without asking anyone to change a key. They stand up a Spanway database, run the dry run on Friday to see the row counts and confirm the salt key decrypts a stored credential, copy the tables on Saturday morning while the old gateway keeps serving, translate the config and env file, and start Spanway against the new database. On Saturday afternoon they switch the load balancer. Every existing key keeps working, and the spend history is there in the Admin UI on Monday.

Before you start​

Run spanwayctl from the gateway image, which carries the CLI and the Postgres driver the copy uses. The CLI reference shows the shell function the commands below assume.

spanwayctl --version

Create an empty Postgres database for Spanway and apply the Spanway schema to it with the spanway-migrations image, which carries the schema and runs the migrations (docker run --rm -e DATABASE_URL=postgresql://... registry.spanway.ai/spanway/spanway-migrations:2.0.0). The images page describes it. The copy refuses to write anything when a Spanway table is missing, and tells you which one.

Find the salt key the old gateway used. That is its *_SALT_KEY variable, or its master key when no salt key was ever set. Provider credentials and model parameters stored in the database are encrypted with it, and the copy moves them as ciphertext. Spanway decrypts them as long as it runs with the same key.

export SPANWAY_SALT_KEY="<value of the old gateway's salt key>"

If the old gateway never had a salt key, set SPANWAY_MASTER_KEY to the old master key instead, since Spanway falls back to the master key in the same way. See production settings for why a separate salt key is the better long-term setup.

Dry run​

The dry run connects to both databases and prints, for every table, the rows in the source, the rows already in the target, the source columns that have no Spanway counterpart and will be left behind, and the Spanway columns the source does not fill. It writes nothing.

spanwayctl migrate gateway-db \
--source-db-url postgresql://gateway:...@old-db:5432/gateway \
--target-db-url postgresql://spanway:...@new-db:5432/spanway \
--dry-run --report migrate-dry-run.json

--target-db-url defaults to DATABASE_URL. Prisma-only URL parameters such as connection_limit are dropped, and schema= is honoured.

The command also checks the salt key. When SPANWAY_SALT_KEY (or SPANWAY_MASTER_KEY) is set in the shell, it decrypts one stored credential with it and says whether that worked, so a wrong key shows up now rather than as decryption errors after the switch.

Copy​

Run the same command without --dry-run.

spanwayctl migrate gateway-db \
--source-db-url postgresql://gateway:...@old-db:5432/gateway \
--target-db-url postgresql://spanway:...@new-db:5432/spanway \
--report migrate-report.json

By default the command copies these tables, in this order so that every foreign key finds its parent: budgets, object permissions, organizations, the model table, teams, projects, users, organization memberships, team memberships, end users (customers), tags, credentials, database models and virtual keys.

Add --include-spend to also copy the request logs (SpendLogs) and the daily spend tables for users, teams, organizations, end users, tags, agents and the global total. These can be large, so they are opt-in. --tables TeamTable,UserTable limits the run to the named tables, and --batch-size (default 1000) sets how many rows go into one insert batch.

Every batch is inserted with ON CONFLICT DO NOTHING and committed on its own. Rows that already exist in the target are skipped, which makes the command safe to rerun. The same rule also skips a source row that clashes with a different target row on another unique column, and the report counts it under already present. For example, a credential in the target with the same credential_name but a different id means the source credential is not copied. Copy into an empty Spanway database, or check the already present counts against the dry run's target rows, so nothing is lost this way. If a table fails, the command stops there, prints the database error (the error message and the constraint or column it names, never the row itself) and exits with status 1. Fix the cause and run it again, the rows that made it across are skipped and the copy carries on.

Only columns that exist on both sides are copied. A column the old gateway names with its own prefix is written to the matching spanway_... column, and inside stored model parameters the old credential name key becomes spanway_credential_name. Everything else, including token hashes, budgets, spend counters and timestamps, is copied unchanged. When a source value is empty but Spanway requires the column and has a default for it, the Spanway default is used.

The model table that holds team model aliases uses numeric ids, and teams point at those ids. The copy keeps them, then moves the id sequence past the highest copied id so the gateway can keep creating rows. If the target already holds a different row under one of the copied ids, the command refuses to copy anything and names the ids, since teams would otherwise pick up another row's aliases. Migrate into a target database that does not hold those rows.

The JSON report written by --report lists, per table, its status, rows read, rows inserted, rows that were already present and the dropped columns.

Audit log​

Every run that copies something writes one row per copied table to the target database's audit log, so the record of who moved which tables, and when, is there from the first day. All rows of a run share the object_id gateway_migration:<id>, which the command prints as Audit log rows written under gateway_migration:<id> and puts in the report under audit.run_id. Each row names the copied Spanway table, the source table and the rows read and inserted, never the data in a row. changed_by reads spanwayctl migrate gateway-db (<who>), where <who> is your login name, or the value of --changed-by when you pass one, for example --changed-by ops@example.com. The rows are hash chained like every other audit row. A dry run writes none.

Coming from Spanway Cloud​

Moving a workspace from Spanway Cloud to your own gateway does not use these commands. Export the workspace with GET /cloud/tenant/export and send the bundle to POST /cloud/import on the self-hosted gateway, which creates the organization, teams, members, budgets and rate limits in one transaction. See export and migration to self-hosted.

What is not copied​

MCP servers and their user credentials, guardrails, prompts, agents, managed files and vector stores, policies, and settings stored in the database (the old gateway's config table) are not copied. Recreate them on Spanway through the Admin UI or the API. Secrets are copied as ciphertext and never re-encrypted. The only decryption is the salt key check on a single credential, whose plaintext is thrown away and never printed.

Translate config.yaml and .env​

spanwayctl migrate gateway-config config.yaml --output spanway-config.yaml \
--env-file .env --env-output spanway.env

The config translation renames every key that carries the old gateway's prefix to spanway_ (its *_settings, *_params and credential name keys), rewrites os.environ/<OLD>_X references to os.environ/SPANWAY_X, and rewrites the old gateway's own proxy provider name (as a provider or as a model prefix) to spanway_proxy. Everything else is left as it was, so model names or values that merely contain the old name are not touched. Values that point at a Python module path of the old gateway, such as a custom callback, are listed for you to review, since that module does not exist in Spanway.

The env translation renames the old gateway's *_ variables to SPANWAY_* and keeps comments, quoting and the order of the file. The old gateway's license variable is dropped, because its license key does not apply to Spanway. The command prints the variable names it renamed but never their values. The translated config, the translated env file and the --report file are written with mode 600, even when the file already existed with wider permissions, since configs often carry inline keys. Without --env-output only the env renames are listed.

spanwayctl models import accepts the old config directly too, so spanwayctl models import config.yaml adds models written in the old *_params form to a running gateway.

Verify with an existing key​

Start Spanway against the target database with the carried-over salt key, then call it with a key that was issued by the old gateway.

curl http://localhost:4000/key/info -H "Authorization: Bearer sk-<an existing key>"
curl http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer sk-<an existing key>" \
-H "Content-Type: application/json" \
-d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "ping"}]}'

The first call returns the key's alias, team and spend as they were on the old gateway. A credential decryption error in the gateway log on the second call means the salt key does not match.

After the switch​

Once traffic runs through Spanway, you can move off the inherited secrets. If you carried the old master key over as SPANWAY_MASTER_KEY because the old gateway had no salt key, master key rotation re-encrypts the stored secrets under a new master key. Virtual keys can be regenerated per team or per user on your own schedule.

Step by step​

  1. Create the Spanway database and apply its schema with the spanway-migrations image, as shown in Before you start. Export the old gateway's salt key as SPANWAY_SALT_KEY.

  2. Run the dry run shown above with --report migrate-dry-run.json. Expected result: a table per source table with the row counts, no writes, and the line that says the salt key decrypted a stored credential.

  3. Run the copy without --dry-run. Expected result: every table reports its inserted and already present rows, the command prints Audit log rows written under gateway_migration:<id>, and it exits 0.

  4. Translate the config and the env file with spanwayctl migrate gateway-config, review the module paths it lists, and start Spanway with the translated files.

  5. Verify with a key issued by the old gateway:

    curl http://localhost:4000/key/info -H "Authorization: Bearer sk-an-existing-key"

    Expected result: the key's alias, team and spend as they were on the old gateway.

  6. Open the Admin UI, sign in with the master key, and check Teams, Virtual Keys and Usage. The teams, keys and spend history are there. Then switch your load balancer or DNS to Spanway.

Errors​

SymptomMeaningFix
The source session is not read only, so nothing was read or written.The connection pooler dropped the read-only option.Point --source-db-url at the database directly.
Nothing was copied. Apply the Spanway migrations to the target database first by running the spanway-migrations image against it.The Spanway schema was not applied to the target, or an older schema is missing a table or a required column. The report shows missing_in_target or required_columns_missing with the column names.Run the spanway-migrations image against the target as shown in Before you start, then run the dry run again.
Error: Invalid value for '--tables': unknown table(s) <names>. Known: <names>--tables names a table the command does not copy.Use the names from the Known: list, for example TeamTable,UserTable.
Error: No module named 'psycopg'. The database migration needs the gateway's database drivers. Run spanwayctl from the spanway-ai container image...spanwayctl runs from an environment without the Postgres driver.Run it from the gateway image, as shown in Before you start.
Error: could not connect: <reason>One of the two databases cannot be reached, or the user, password or database name is wrong.Check the host, port and credentials in --source-db-url and --target-db-url, and that the machine running the command can reach both.
Neither SPANWAY_SALT_KEY nor SPANWAY_MASTER_KEY is set here.The salt key check had no key to try, so it could not tell whether the gateway will decrypt the copied credentials. The copy still runs.Export the old gateway's salt key as SPANWAY_SALT_KEY (or its master key as SPANWAY_MASTER_KEY) and run the dry run again.
The rows were copied, but the audit log rows could not be written (<error class name>)., for example (UniqueViolation)The copy finished, but the audit rows for it could not be added, and the command exits 1.Rerun the same command. Copied rows are skipped and the rerun writes the audit rows.
Error: <file> is not a YAML mapping of plain values: <reason> from gateway-configThe config file is not valid YAML, or its top level is not a mapping.Fix the YAML, check it with any YAML linter, and run the command again.
The configured salt key does not decrypt the copied credentials. in the dry runSPANWAY_SALT_KEY or SPANWAY_MASTER_KEY differs from the old gateway's value.Export the old gateway's salt key, or its master key when it never had a salt key.
The copy stops on a table with a constraint error and exits 1A row violates a Spanway constraint, the message names the constraint or column and never the row.Fix the cause and rerun, rows already copied are skipped.
<table> already holds different rows under <column> <ids>The model alias table in the target has conflicting numeric ids.Migrate into an empty target database.
Credential decryption errors in the gateway log after the switchSpanway runs with a different salt key than the one the credentials were encrypted with.Set the old salt key, then rotate later with master key rotation.

Logs​

Both commands print to the terminal only, and the gateway's own logs are not involved.

LineWhenMeaning
Existing gateway -> Spanway plan tableEvery gateway-db runPer table the status, source rows, target rows, dropped source columns and target-only columns.
The configured salt key decrypts the copied credentials.gateway-db, when credentials are in scope and a key is setThe salt key check passed. The yellow variants are listed under Errors.
Dry run, nothing was written.gateway-db --dry-runNothing was copied and no audit row was written.
Existing gateway -> Spanway copy tableA gateway-db run that copiesPer table the rows read, inserted and already present, or the database error for a failed table.
Audit log rows written under gateway_migration:<id>A gateway-db run that copied at least one tableThe audit rows described in Audit log were written.
Report written to <path>Any run with --reportThe JSON report with dry_run, salt_key (decrypts, does_not_decrypt, no_key or no_credentials), audit after a copy (status written with the run_id, failed or nothing_copied), and one tables entry per table, written with mode 600.
Config renames (<n>) table and Translated config written to <path>gateway-configEach renamed key with its path.
Review <path>: it points at a Python module path of the old gateway.gateway-configA value names old gateway code, recreate it on Spanway.
env <OLD> -> <NEW> and env <NAME> dropped, ...gateway-config --env-fileEach renamed or dropped variable, by name only, never its value.