Skip to content

server side "disconnect client" functions #5266

Open

Description

@website-features

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

  1. EnoroF commented on Oct 4, 2026

    @EnoroF

    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.

  2. tamaro-skaljic commented on Oct 28, 2026

    @tamaro-skaljic
    Contributor

    Disclaimer: AI Usage

    • This proposal was drafted with AI from a design conversation, and I reviewed and edited it.

    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 ReducerContext and TxContext a disconnect method.

    • 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 disconnect and when it acts are in the doc comments, where the IDE shows them.

    Types

    In the spacetimedb crate, next to ReducerContext:

    /// The connections that `disconnect` closes.
    #[derive(SpacetimeType)]
    pub enum By {
        /// Every connection of this identity.
        /// Inside `client_connected`, the connection being set up is left out.
        Identity(Identity),
    
        /// This one connection.
        ConnectionId(ConnectionId),
    }
    
    impl From<Identity> for By { /* By::Identity */ }
    
    impl From<ConnectionId> for By { /* By::ConnectionId */ }
    
    /// Whether `disconnect` waits for the calling transaction to commit.
    ///
    /// | Calling transaction | `Yes`                        | `No`                           |
    /// |---------------------|------------------------------|--------------------------------|
    /// | commits             | disconnects after the commit | disconnects after the commit   |
    /// | fails               | doesn't disconnect           | disconnects after the rollback |
    #[derive(SpacetimeType)]
    pub enum Transactional {
        Yes,
    
        No,
    }
    
    /// What the `disconnect_client` reducer receives for one call of `disconnect`.
    #[derive(SpacetimeType)]
    pub struct Disconnected {
        /// The identity whose connections are closed.
        /// `None` when `disconnect` named a `ConnectionId` that has no open connection when it runs.
        pub identity: Option<Identity>,
    
        /// The closed connections; empty when there are none.
        pub connection_ids: Vec<ConnectionId>,
    }
    
    /// Why SpacetimeDB refused to run a `disconnect`. Nothing changed.
    #[derive(SpacetimeType)]
    pub enum DisconnectError {
        /// Called inside `disconnect_client` or `client_disconnected`.
        OngoingDisconnect,
    
        /// Called inside `client_connected` with the `ConnectionId` of the connection being set up.
        /// To refuse that connection, return an error from `client_connected`.
        OwnConnection,
    }

    DisconnectError implements Display with a message that says what to write instead, and converts into String, so ? works in a reducer that returns Result<(), 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_client reducer

    A new section in the docs of #[reducer], next to client_connected and client_disconnected:

    /// ### The `disconnect_client` reducer
    ///
    /// This reducer is marked with `#[spacetimedb::reducer(disconnect_client)]`.
    /// It adds a `disconnect` method to [`ReducerContext`] and [`TxContext`],
    /// and runs once for each call of that method.
    /// A module without it has no `disconnect` method.
    ///
    /// Its second parameter is a [`Disconnected`].
    /// An optional third parameter takes a payload that each call of `disconnect` passes on.
    /// Its type `P` is any type that implements `SpacetimeType`:
    /// a built-in one such as `String` or `u32`,
    /// or a struct or enum of the module with `#[derive(SpacetimeType)]`.
    /// The parameters decide the signature of `disconnect`:
    ///
    /// | `disconnect_client` takes                     | `disconnect` is                                                                                                    |
    /// |-----------------------------------------------|--------------------------------------------------------------------------------------------------------------------|
    /// | `ctx, disconnected: Disconnected`             | `fn disconnect(&self, by: impl Into<By>, transactional: Transactional) -> Result<(), DisconnectError>`             |
    /// | `ctx, disconnected: Disconnected, payload: P` | `fn disconnect(&self, by: impl Into<By>, transactional: Transactional, payload: P) -> Result<(), DisconnectError>` |
    ///
    /// The payload stays in the module: the disconnected clients never see it.
    /// [`Transactional`] says whether the disconnect waits for the calling transaction to commit.
    ///
    /// `ctx.sender()` is whoever called `disconnect`.
    /// The disconnected clients are in [`Disconnected::connection_ids`].
    ///
    /// This reducer runs in a transaction of its own,
    /// so it can record a ban even when the reducer that called `disconnect` fails.
    /// If an error occurs in this reducer, its changes are discarded,
    /// and the clients are still disconnected.
    ///
    /// A disconnect ends only the connections that are open now.
    /// To keep a client out, write to a table here, and return an error from `client_connected` when it connects again.
    

    The intro of the lifecycle section changes too: it says lifecycle reducers take no parameter except ReducerContext, and disconnect_client takes Disconnected and an optional payload.

    Generated disconnect

    • The disconnect_client reducer's macro emits disconnect as a generated trait implemented for ReducerContext and TxContext, 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, DisconnectError and the disconnect_client section.

    • ProcedureContext gets no disconnect. A procedure disconnects inside with_tx / try_with_tx.

    • Anonymous views get no disconnect. Whether views get one is open, see below.

    • A module defines at most one disconnect_client reducer, like the other lifecycle reducers. Clients can't call it.

    Example

    #[derive(SpacetimeType)]
    pub struct Ban {
        pub reason: String,
    }
    
    #[reducer(disconnect_client)]
    fn on_disconnect_client(ctx: &ReducerContext, disconnected: Disconnected, ban: Ban) -> Result<(), String> {
        // e.g. write a ban log; `client_connected` reads it and refuses banned identities.
        Ok(())
    }
    
    #[reducer]
    fn admin_only(ctx: &ReducerContext) -> Result<(), String> {
        if !is_admin(ctx) {
            // The target is anything that converts into `By`:
            // - every connection of the caller's identity: `ctx.sender()`, or written out `By::Identity(ctx.sender())`,
            // - only the calling connection: `connection_id`, or written out `By::ConnectionId(connection_id)`,
            //   taken from `ctx.connection_id()`, which is an `Option`: `None` in `init` and scheduled reducers.
            ctx.disconnect(ctx.sender(), Transactional::No, Ban { reason: "forged admin call".into() })?;
    
            return Err("not an admin".into());
        }
    
        Ok(())
    }

    Behavior

    When it happens

    • Transactional above says whether a disconnect happens when the transaction called it returns an error.

    • The request records the target, the Transactional value and the payload in the calling transaction. It changes no table.

    • disconnect_client runs once per disconnect call.

    • In disconnect_client, ctx.sender() is whoever called disconnect: an admin, or the database for a scheduled reducer.

    • connection_ids holds every connection of the identity for By::Identity, and the one connection for By::ConnectionId. For By::Identity it is empty when the identity has no open connection; disconnect_client runs anyway, e.g. to ban an identity that isn't connected.

    • For By::ConnectionId, the identity comes from that connection's st_client row. When the connection never existed, or left before the request runs, there is no row: identity is None, connection_ids is empty, and disconnect_client runs anyway, so its payload isn't lost.

    • Connections include HTTP /call, SQL and MCP callers, which have an st_client row 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_connected

    • By::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_connected returns an error of its own, as today. A call of disconnect with the new connection's own ConnectionId fails with DisconnectError::OwnConnection, whose message says exactly that.

    • To also close the identity's other connections, if there are some, the By::Identity call needs Transactional::No: the refusal makes client_connected fail, which drops a Yes request.

    #[reducer(client_connected)]
    fn connected(ctx: &ReducerContext) -> Result<(), String> {
        if is_banned(ctx) {
            // Closes the identity's other connections.
            // `No`, because the error returned below makes this reducer fail.
            ctx.disconnect(ctx.sender(), Transactional::No, Ban { reason: "banned".into() })?;
    
            // Refuses this connection.
            // Calling `disconnect` with this connection's own `ConnectionId` fails too,
            // but its `DisconnectError::OwnConnection` says to return an error of your own instead.
            return Err("banned".into());
        }
    
        Ok(())
    }

    Refused calls

    disconnect returns an error, and changes nothing, when it is called:

    • inside disconnect_client or client_disconnected, so no request starts another,

    • inside client_connected, with the ConnectionId of the connection being set up; the error says to return an error from client_connected instead.

    Procedures

    Inside with_tx / try_with_tx, TxContext behaves like ReducerContext: when the body returns an error, Yes doesn't disconnect, and No does.

    Transactions of one disconnect

    Success case, one transaction:

    1. disconnect_client runs.

    2. client_disconnected runs for each connection, if the module defines it.

    3. SpacetimeDB deletes each connection's st_client row.

    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_disconnected lifecycle reducers:

    1. disconnect_client alone. Its failure is discarded, and nothing stops.

    2. For each connection, the normal disconnect teardown, including today's fallback transaction that deletes the st_client row when client_disconnected fails.

    The connections are closed in every case, also when disconnect_client fails.

    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_client row gone and does nothing, so client_disconnected runs 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 ClientDisconnectCause variant for metrics.

    Bans

    A disconnect only ends the connections that are open now.

    To keep a client out, disconnect_client writes to a module table, and client_connected checks it and returns an error.

    Host Side (for orientation)

    • New host call in spacetime_10.7 (wasm), with its wrapper in bindings-sys. V8 (sys@2.3) follows with the TypeScript PR.

    • New Lifecycle variant 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_client doesn't run for it.

    • connection_ids comes from st_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 the session_id index lives in client-api. This needs a registry of all WebSocket connections per database.

    • The existing kick aborts the connection task without a close frame. This feature sends one.

    Questions for the Maintainers

    • Views: should ViewContext get disconnect? 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.

  3. Ryan-Alfaddaghi commented on Nov 15, 2026

    @Ryan-Alfaddaghi

    +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:

    • The token is only checked at connect, so an already-open connection keeps working after its session or token is revoked.
    • We can record each ConnectionId's session in client_connected and refuse reducers/procedures from a revoked one, but views and subscriptions only see ctx.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_id as 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 ConnectionId on 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions