Replay-Driven State Seeding for Kalshi Integration Tests That Never Touch Production
Test stateful APIs without production risk by replaying recorded exchanges into a local simulator.

Integration testing against stateful APIs needs a test environment that remembers what earlier calls changed. For Kalshi, replay-driven state seeding captures demo exchanges once, then uses them to initialize a local simulator that validates signing, order transitions, and reconnect behavior. This makes repeatable integration tests possible without production credentials, live network access, or rate-limit consumption during test runs.
Why Kalshi's API design makes stateless mocks structurally inadequate
Kalshi requires every authenticated request to include a key ID, a timestamp, and an RSA-PSS signature constructed by signing the concatenation of timestamp, HTTP method, and request path with a private key. Authentication is therefore more than a header swap. A stub that returns a canned 200 for any signed request cannot distinguish correct signing from a broken implementation. It can report success before the client has demonstrated that it could authenticate.
The same gap extends beyond individual HTTP requests. Kalshi requires API key authentication for the WebSocket connection itself, even when the selected channels deliver public data. After authentication, order mutations change the state that later requests must read, while streaming adds subscription and delivery history. Token-cost rate limits, tiered by account level, also constrain live testing. The Write budget is less generous than the Read budget, so repeated order tests consume the more constrained resource.
How to test Kalshi when order of operations matters
A meaningful lifecycle test begins with authenticated session context, discovers a market, places a limit order, and receives an order ID. It then polls that ID through status changes, amends or cancels the order, and checks the resulting position. Each response becomes a precondition for the next request. The creation response cannot be independent of the status response, and cancellation cannot be independent of the order’s current state. The sequence is the unit under test.
A fixed status fixture breaks that dependency. It can make a polling loop finish at once or run forever without testing a real transition. Likewise, an unrelated order ID on a later read disconnects the test from the order it created. The decisive criterion is whether the environment supports “create then read, mutate then read.” An attempt to cancel an already-settled order adds a stricter check, because the environment must remember settlement before it can produce the conflict.
WebSocket reconnection adds another sequence to preserve. The client must resume the correct subscriptions and receive incremental order-book deltas relative to the messages already delivered. Replaying a recording from its beginning does not establish that behavior. The state at reconnection must be pinned.
Why the demo environment alone does not solve the reproducibility problem
The demo environment has a legitimate verification role. It is suitable for first-time signing checks, manual exploration, and checking lifecycle and connection handling without production credentials. Kalshi’s demo documentation states that demo and production credentials are separate and warns that demo market prices and behavior may differ from real markets, making demo observations unsuitable as production-market fixtures.
That separation removes financial risk. Demo tests still depend on whether the network is available, how market state changes, shared credential state, and tier-based rate limits. A failed CI job may reflect an unavailable endpoint rather than a client defect, while concurrent jobs may compete for the same budget. Some tier restrictions also differ from production, which limits what a successful demo run proves. Demo is therefore the capture and verification environment, rather than the foundation for every repeatable test run.
What a replay bundle captures and why it must be more than an HTTP recording
An HTTP recording omits the starting state that gave each exchange its meaning. Without fixture identity, correlation context, and frozen randomness and time, replay can start with different preconditions and still return responses with a valid structure. A replay bundle binds those inputs to the exchanges. For mutations, it also makes fixture setup and cleanup explicit, preventing an already-applied change from silently becoming the next run’s starting point.
Seed controls provide a concrete way to pin variation. A request flag can supply a known integer seed that forces the simulator down a known path, with that control off by default in production. Timestamp snapshots serve the corresponding role for components that depend on wall-clock time. Neither control replaces ordering, because the same calls in a different sequence can change the outcome.
The complete bundle includes redacted requests and responses, client and server correlation IDs, random seed values, timestamp snapshots, timing and ordering, fixture identity, and explicit setup and cleanup. It also records immutable environment versions, including the API version, endpoint revision, and client SDK version. Any captured WebSocket handshake and delta sequence belongs with that context, rather than in a separate recording whose relationship to the order state is unknown.
Recording the state-changing calls and redacting credentials
The capture process begins with a bounded demo session intended to produce a reusable bundle. Its scope is authenticated mutation, including order placement, amendment, and cancellation. Market discovery and public market data can come from fixtures that are already seeded. The mutation responses need their full context because their order IDs and correlation state link the calls that follow. Capture is not a reason to record every endpoint.
Before committing the bundle, remove private-key material and key IDs from captured headers and any other captured credential fields. The signing inputs must remain reconstructable, including the timestamp, method, path, and their concatenation order. Tests can then exercise signing with a test key. Replace real account identifiers with stable fixture identifiers that also exist in the simulator’s seed data.
Next, capture the WebSocket handshake, its authentication exchange, and the first delta sequence after connection to give reconnect tests the context needed to exercise authentication. Stamp the bundle header with the API version and endpoint revision, and retain the client SDK version as part of its environment identity. Those versions make an outdated capture visible before it is mistaken for a current contract.
Loading the bundle into a stateful simulator and constructing the starting world
Playback begins by loading the records named in the bundle’s fixture identity, including accounts, markets, and positions. These records establish the world that existed before the captured mutations. Starting empty forces each test to rebuild preconditions and can cause recorded calls to refer to accounts or markets that do not exist. The seed must precede the replay.
Open markets need valid tick sizes, order-book depth, and realistic position sizes so that order constraints are exercised against useful preconditions. An order created earlier must remain retrievable later, and an amendment must change what the next read returns.
Each run should start from a clean copy of the seeded world, with teardown and re-seeding keeping changes from earlier runs out of later tests. Stateful tests should run serially or in isolated containers with isolated data. Otherwise, interference between concurrent runs can look like intermittent client failure even though the test environment is responsible.
Writing tests that validate auth, order lifecycle, and the conflict paths
Authentication assertions should distinguish a valid signature from plausible-looking headers. A request that is correctly signed should reach the order endpoint and get a valid order ID. A request that concatenates timestamp, method, and path in the wrong way should get a 401 with as little detail about the failure as the live API gives. An expired timestamp should also be rejected. The simulator must not make authentication more permissive merely to simplify testing.
Lifecycle assertions then follow the seeded order state. The returned order ID should match the expected ID for that seed, and polling should expose the expected status progression. An amendment to price or quantity should appear in the next read. A cancellation attempt after settlement should produce the appropriate conflict response. These assertions test the causal link between mutation and retrieval.
An order in a closed market should fail validation, while a second order that would exceed a position limit should be rejected based on the running total. Reconnect assertions should check both re-authentication with the test key and restoration of the correct subscription. The deltas that arrive should pick up from the reconnection point without repeating messages already received.
Injecting faults into the replay path to test retry and reconnect logic
Kalshi’s developer guidance recommends retry handling, exponential backoff, and WebSocket reconnection logic. These paths therefore belong in integration coverage. A live endpoint cannot reliably produce each failure on demand. The replay harness should make faults configurable per test, holding other variables constant so that a retry test does not become an accidental lifecycle test.
Fixed delays on signed calls can reveal stale timestamps or inappropriate timeout behavior. Dropping a WebSocket connection mid-session tests whether the client re-authenticates and re-subscribes. Rate-limit responses on trading calls test whether the client backs off under the token-cost system. Service-unavailable responses during order polling test exponential backoff.
HTTP success must not end response validation. A structurally valid 200 can contain an order ID unrelated to the created order or a status that is syntactically valid but impossible at that point in the lifecycle. The test should establish that the client rejects the corrupted content. This fault depends on remembered state, making it a particularly sharp reason to integrate fault injection into the replay harness itself.
Preventing simulator drift from invalidating the test suite over time
A passing simulator test proves compatibility with the simulator’s contract. Live APIs change through endpoint revisions, implementation changes, and SDK releases. That change is normal. Fixtures maintained by hand can keep accepting an outdated mutation route unless their behavior is checked against the current contract. The bundle’s version header provides an initial compatibility check before replay begins.
Scheduled contract testing addresses the remaining gap. Tests against the real demo service can detect differences between the published specification and the running implementation. The same contract tests against the simulator can expose differences between its behavior and the specification it implements. This verification should run on a schedule and accompany simulator releases. Regular integration runs can stay offline while a separate process checks the simulator using demo access.
A CI receipt makes changes traceable across runs. It should record the route exercised, simulator API version, commit SHA, elapsed time, and any request IDs. When a contract changes intentionally, the fixture and expected receipt should change together. An unexplained difference then becomes a signal to investigate before downstream tests inherit false confidence. A capture is reusable, but its claim to represent the current API still needs maintenance.
Applying the same replay-seeding pattern to AI agent and RL workflows that call Kalshi
An AI agent that calls Kalshi has the same order dependencies as a human-written client, along with model non-determinism. Its multi-step tool chain can also consume external data that changes between runs. A pinned simulator separates that environmental variation from model behavior. It gives evaluations a stable world against which to compare decisions.
An agent may accept a correctly formatted but unrelated order ID and act on the wrong state unless it validates content. Seeded fault tests can reveal that failure while keeping the history of actions that came before it. The evaluation can therefore test whether the agent reasons from a valid order state, validating content alongside the HTTP status.
Reinforcement learning adds reset and scale requirements. The same seed must produce the same market states, order outcomes, and position updates, while each episode must return to a known starting world without calling the live API. Thousands of episodes running in parallel need isolated instances so that they do not interfere through shared state or compete for rate limits. A verified stateful simulator with realistic seeds and per-run teardown provides those controls, making the environment reproducible even when the policy being evaluated is not.


