Description
we need a way to disconnect clients from the server side. ideally both through, ctx.disconnect_identity(identity: Identity) and ctx.disconnect_connection_id(connection_id: ConnectionId).
this is required to be able to build ban systems as custom clients can just not react to any "server says disconnect" setups.
a timeout system also requires this but can be worked around with the "server says disconnect" setups but it isn't nice and can be ignored on the client side as mentioned.
the disconnect_connection_id alternative is needed when multiple clients can connect to the same identity at the same time and we don't want to disconnect all connections or something like that. (it's mostly to have the option)
doing a direct ctx.disconnect_sender() is not as useful as it doesn't work with scheduled reducers/procedures.
Requested by @xDovos via the SpacetimeDB site.
Activity
EnoroF commentedon Oct 4, 2026
I have the same requirement for a multiplayer game: when a player logs in on a new device with the same Identity, the server should disconnect the previous connection while keeping the new one active.
Tracking the latest ConnectionId and rejecting reducers from older connections only prevents gameplay actions that perform that check. It does not close the old WebSocket or stop its subscription updates. Asking the old client to disconnect is also insufficient because it can ignore the notification.
The session_id-based reconnect mechanism addresses replacement within the same logical session, but different devices can use different session IDs, so it does not enforce one active connection per account.
A module-accessible API to disconnect a specific ConnectionId would let us implement this policy in the server-side client_connected/login logic. Disconnecting by Identity would also be useful for bans, but targeted disconnection is particularly important here so the newly accepted connection is preserved.
tamaro-skaljic commentedon Oct 28, 2026
Disclaimer: AI Usage
Proposal
Modules get a way to disconnect clients from the server side, for bans, timeouts and "one connection per identity".
A new lifecycle reducer
#[reducer(disconnect_client)]receives every disconnect request, together with a payload type that the module defines.Defining it gives
ReducerContextandTxContextadisconnectmethod.A disconnect either waits for the transaction to commit, or happens even if the transaction fails. (why see below)
Rust comes first. TypeScript and C# follow in separate PRs once the Rust part is merged. C++ is out of scope for me, as I'm not familiar with it.
Why a lifecycle reducer
A reducer that disconnects a client often fails on purpose, e.g. when a client forges a call to an admin reducer that its UI never offers.
Without the lifecycle reducer, the failing reducer would have to write the ban itself, and its rollback would discard that write. Every reducer that may disconnect and ban clients would have to succeed just to keep the ban.
With it, the ban is written in
disconnect_client, in a transaction of its own, so the calling reducer is free to fail.API (Rust)
The API documents itself in the code: the signature of
disconnectand when it acts are in the doc comments, where the IDE shows them.Types
In the
spacetimedbcrate, next toReducerContext:DisconnectErrorimplementsDisplaywith a message that says what to write instead, and converts intoString, so?works in a reducer that returnsResult<(), String>.The payload is no field of
Disconnected, but a parameter of its own (see below):#[derive(SpacetimeType)]doesn't support generic types in modules.The
disconnect_clientreducerA new section in the docs of
#[reducer], next toclient_connectedandclient_disconnected:The intro of the lifecycle section changes too: it says lifecycle reducers take no parameter except
ReducerContext, anddisconnect_clienttakesDisconnectedand an optional payload.Generated
disconnectThe
disconnect_clientreducer's macro emitsdisconnectas a generated trait implemented forReducerContextandTxContext, the same way a table emits its accessors.The generated method carries a doc comment with its signature for this module, and links to
By,Transactional,DisconnectErrorand thedisconnect_clientsection.ProcedureContextgets nodisconnect. A procedure disconnects insidewith_tx/try_with_tx.Anonymous views get no
disconnect. Whether views get one is open, see below.A module defines at most one
disconnect_clientreducer, like the other lifecycle reducers. Clients can't call it.Example
Behavior
When it happens
Transactionalabove says whether a disconnect happens when the transaction called it returns an error.The request records the target, the
Transactionalvalue and the payload in the calling transaction. It changes no table.disconnect_clientruns once perdisconnectcall.In
disconnect_client,ctx.sender()is whoever calleddisconnect: an admin, or the database for a scheduled reducer.connection_idsholds every connection of the identity forBy::Identity, and the one connection forBy::ConnectionId. ForBy::Identityit is empty when the identity has no open connection;disconnect_clientruns anyway, e.g. to ban an identity that isn't connected.For
By::ConnectionId, the identity comes from that connection'sst_clientrow. When the connection never existed, or left before the request runs, there is no row:identityisNone,connection_idsis empty, anddisconnect_clientruns anyway, so its payload isn't lost.Connections include HTTP
/call, SQL and MCP callers, which have anst_clientrow while their request runs, so modules can react to malicious HTTP requests too. Their row is deleted like any other, but their running request isn't cut off: it finishes, and its own teardown then finds the row gone.Inside
client_connectedBy::Identity(ctx.sender())covers every connection of the identity except the one being set up. This gives "one connection per identity": the new device stays, the old ones go.To refuse the new connection itself,
client_connectedreturns an error of its own, as today. A call ofdisconnectwith the new connection's ownConnectionIdfails withDisconnectError::OwnConnection, whose message says exactly that.To also close the identity's other connections, if there are some, the
By::Identitycall needsTransactional::No: the refusal makesclient_connectedfail, which drops aYesrequest.Refused calls
disconnectreturns an error, and changes nothing, when it is called:inside
disconnect_clientorclient_disconnected, so no request starts another,inside
client_connected, with theConnectionIdof the connection being set up; the error says to return an error fromclient_connectedinstead.Procedures
Inside
with_tx/try_with_tx,TxContextbehaves likeReducerContext: when the body returns an error,Yesdoesn't disconnect, andNodoes.Transactions of one disconnect
Success case, one transaction:
disconnect_clientruns.client_disconnectedruns for each connection, if the module defines it.SpacetimeDB deletes each connection's
st_clientrow.If anything in that transaction fails, the whole transaction is discarded, and the host continues with separate transactions, as it already does today for
client_disconnectedlifecycle reducers:disconnect_clientalone. Its failure is discarded, and nothing stops.For each connection, the normal disconnect teardown, including today's fallback transaction that deletes the
st_clientrow whenclient_disconnectedfails.The connections are closed in every case, also when
disconnect_clientfails.The sockets close after this work, as they do when a migration disconnects all clients today. The connection's own teardown then finds its
st_clientrow gone and does nothing, soclient_disconnectedruns exactly once per connection.When a reducer disconnects its own caller, the caller receives the reducer's result before the close frame.
What the client sees
A WebSocket close frame with a new close code next to
SESSION_BUSY_CLOSE_CODE(4000), and a fixed reason. The payload never reaches the client.A new
ClientDisconnectCausevariant for metrics.Bans
A disconnect only ends the connections that are open now.
To keep a client out,
disconnect_clientwrites to a module table, andclient_connectedchecks it and returns an error.Host Side (for orientation)
New host call in
spacetime_10.7(wasm), with its wrapper inbindings-sys. V8 (sys@2.3) follows with the TypeScript PR.New
Lifecyclevariant in the module def (crates/lib/src/db/raw_def).The host buffers requests in the instance environment and acts on them when the calling transaction ends, after its commit or rollback. Today no hook runs after a commit, and scheduling and the IDC outbox act right away instead.
Requests live in host memory until they run. A crash between the caller's commit and the request loses it: the connections are gone after a restart anyway, but
disconnect_clientdoesn't run for it.connection_idscomes fromst_client. Closing sockets needs more: today nothing maps(Identity, ConnectionId)to a live connection that the module host can reach. The subscription manager covers only subscribed clients, and thesession_idindex lives in client-api. This needs a registry of all WebSocket connections per database.The existing
kickaborts the connection task without a close frame. This feature sends one.Questions for the Maintainers
Views: should
ViewContextgetdisconnect? Views are scoped to an identity or connection, so a view could end a connection that subscribes while it isn't allowed to, e.g. a player who may subscribe to some data only after the client told the server that it is in a certain state.Several nodes: the design assumes that the sockets and the module host of a database run in one process, as in SpacetimeDB Standalone. Do deployments with several nodes need more?
Not Included
TypeScript and C# (separate PRs), C++ (none).
Storing bans or refusing reconnects: modules do this in their own tables and
client_connected.Savepoints inside a transaction.
Disconnects from anonymous views.
Ryan-Alfaddaghi commentedon Nov 15, 2026
+1, and adding a use case that the reducer-side workarounds can't cover.
We use an external OIDC provider for sign-in. When a sign-in session is revoked (sign out everywhere, account lapsed, profile deleted, ban), we need the matching open WebSocket to stop. Today:
ConnectionId's session inclient_connectedand refuse reducers/procedures from a revoked one, but views and subscriptions only seectx.sender, not the connection. So a revoked connection keeps receiving the data its identity can still see, for as long as the socket stays open.disconnect_connection_idas described here would close that gap. Being able to call it from a scheduled reducer or procedure matters to us too: revocation arrives from the identity provider's webhook through a procedure or an HTTP-called reducer, not from the revoked client.A
ConnectionIdon the view context would also be useful, even on its own, but a real disconnect is the clean fix.Happy to test a preview build against the TypeScript module SDK.