Kest

Search

Search the documentation

GraphQL

Subscriptions

Push live updates to clients over a WebSocket.

A subscription is a query that stays open: the server sends a result every time something happens. Use it for live dashboards, chat, order tracking, notifications.

Loading diagram…

Declare and publish

val SCHEMA = """
  type Order { id: ID!  item: String }
  type Query { ping: String }
  type Subscription { orderCreated: Order   counter(upTo: Int!): Int! }
"""
 
@Resolver
class LiveResolvers(private val topics: Topics) {
    @Subscription fun orderCreated(): Publisher<OrderEvent> = topics.publisher("orders")      // a live stream of events
    @Subscription fun counter(upTo: Int): Publisher<Int> = ...                                 // any reactive-streams Publisher, here a finite one
}
 
// anywhere in your application, when an order is created:
topics.publish("orders", OrderEvent("o1", "boots"))

A subscription method returns a Publisher (the standard reactive-streams type). Topics is a ready-made in-process publisher per topic name: topics.publisher("orders") for subscribers, topics.publish("orders", event) for producers. Each event is shaped by the selection set of that subscriber, so one client can ask for { id } and another for { id item }.

Connecting from a client

Clients open a WebSocket to the same path as the endpoint (ws://host:8080/graphql) and speak the graphql-transport-ws protocol (the standard one used by graphql-ws in JavaScript):

import { createClient } from "graphql-ws";
const client = createClient({ url: "ws://localhost:8080/graphql" });
client.subscribe({ query: "subscription { orderCreated { id item } }" },
  { next: (e) => console.log(e.data.orderCreated), error: console.error, complete: () => {} });

The protocol: connection_init, then subscribe with {query, variables, operationName}, then one next per event and finally complete. complete from the client cancels one subscription, closing the socket cancels all, ping is answered with pong, and a bad query is one error message. Subscriptions need the Netty engine (subscriptions = true is the default).

Security

Guards on the resolver (@Authenticated, @Roles) run when the subscription starts, using the connection's handshake (headers, cookies, query string). The connection_init payload is acknowledged but not read, so send credentials the way you would for any WebSocket: a cookie or header at connection time, or ?token=... in the URL.

Several instances

Topics lives inside one process: a publish reaches only subscribers connected to the same instance. With a load balancer and several instances, publish to a broker (Redis, NATS, Kafka) and let each instance's consumer call topics.publish(...) locally, so every instance relays the event to its own clients.

Loading diagram…

The older graphql-ws sub-protocol (the pre-2020 one) is not implemented.

Read more