Subscriptions

Intermediate · 1 min

A subscription streams results as events happen. Define the root, return an async iterator, publish from a mutation, and filter per client.

Before thisMutationsGraphQL over HTTP

Warren Day · 20 min · from 3:17:43

Subscriptions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Warren DayReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A subscription is an operation that stays open and delivers one result for every event, instead of one result and done. It starts at the `Subscription` root type.
  • Each subscription field has a `subscribe` function that returns an async iterator of events, and an optional `resolve` that shapes each event into the field's value.
  • The usual wiring is a publisher: a mutation calls `publish` and every open subscription for that topic receives the event.
  • The server runs your filter per subscriber, so arguments such as `authorId` let each client see only the events it asked for.
  • A subscription holds server resources for as long as the client stays connected, so it suits events that are pushed to the user, not data that is cheap to poll.

The problem: knowing when something changed

A query asks once. If a chat message arrives a second later, the client finds out only by asking again. The usual fix is polling, a request every few seconds. It works, but it wastes requests when nothing changed and still shows stale data for up to one interval.

A subscription flips the direction. The client sends one operation, the server keeps it open, and pushes a result each time the event happens. Same schema, same selection sets, same types. Only the delivery changes: many responses over time instead of one.

The Subscription root

type Post { id: ID! title: String! authorId: ID! }

type Subscription {
  postCreated(authorId: ID): Post!
}

The client writes:

subscription {
  postCreated(authorId: "2") { title authorId }
}

Nothing happens until something publishes. When a post for author 2 is created, the server runs the selection set against that post and sends the result. The shape is a normal GraphQL response, { "data": { "postCreated": { ... } } }, once per event.

Subscribe returns an async iterator

A subscription resolver is an object with two functions instead of one. This is the part that surprises people coming from queries:

  • subscribe returns an async iterator that yields events. It runs once, when the operation starts.
  • resolve runs for every event the iterator yields and turns it into the field’s value. If the event already looks like the field, you can leave it out.

An async iterator is a thing you can loop over with for await; if that is new, iterators and generators covers it. Yoga ships a small in-memory publisher:

import { createYoga, createSchema, createPubSub, pipe, filter } from 'graphql-yoga';

const pubsub = createPubSub();

const resolvers = {
  Mutation: {
    createPost: (_, { authorId, title }) => {
      const post = savePost(authorId, title);
      pubsub.publish('postCreated', post);
      return post;
    },
  },
  Subscription: {
    postCreated: {
      subscribe: (_, { authorId }) =>
        pipe(
          pubsub.subscribe('postCreated'),
          filter((post) => !authorId || post.authorId === authorId),
        ),
      resolve: (post) => post,
    },
  },
};

The mutation does its write, then calls publish. Every open subscription listening to postCreated receives the post. The pipe and filter pair runs per subscriber, so the client that passed authorId: "2" is the only one that sees author 2’s posts.

I ran this with Yoga 6.1.0 on Node 26, opened a subscription for author 2 over server-sent events, and then sent two mutations, one for author 1 titled “not mine” and one for author 2 titled “mine”. The stream got exactly one event:

event: next
data: {"data":{"postCreated":{"title":"mine","authorId":"2"}}}

The first thing on the wire was a bare : comment line, which servers use to keep the connection alive. The next lesson explains where those bytes travel.

Events do not need a pub/sub

Any async iterator works as a source. A generator can produce a countdown, poll a table, or read from a queue:

countdown: {
  subscribe: async function* (_, { from }) {
    for (let i = from; i >= 0; i--) {
      yield { countdown: i };
      await new Promise((r) => setTimeout(r, 100));
    }
  },
},

With from: 2 a client received 2, 1, 0 about 100 ms apart, then a complete signal. When the iterator ends, the subscription ends.

The costs

A subscription is a connection that stays open. Each one holds memory and a socket on the server, and the server must clean up when the client disappears. Three consequences:

  • In-memory pub/sub is one process. Run two copies of the server and a mutation on A publishes only to subscribers on A. Production setups use a shared broker such as Redis, or a managed service, between publish and subscribe.
  • Authorize at subscribe time, and per event. A subscription is not a free pass to data. Check who is subscribing when the operation starts, and check again if permissions can change while it is open.
  • Pick the right tool. A subscription suits events pushed to the user: messages, notifications, live status. For data that changes slowly or for a client that can wait, polling a normal query is simpler and scales with ordinary HTTP infrastructure.

What the video covers

The embedded segment is a stretch of Warren Day’s 2025 full GraphQL course, running from the chapter “Part 15: Introduction to Subscriptions” at 3:17:43 through “Part 16: Implementing Subscriptions”, ending at 3:37:34 where the chapter “Part 17: Error Handling” begins. From the chapter titles, it introduces subscriptions and then builds one. It is a clip of a 4 hour 20 minute video, picked from the chapter list rather than a transcript, so it may use a different server library from Yoga. The code above is the reference for this lesson. Ben Awad’s older explainer is in the links below for a second view, and the general trade-offs between push styles are in streaming and real-time API contracts.

Where this fits

Subscriptions describe what the client asks for. How events physically travel to the browser is a separate decision with real trade-offs. Next: subscriptions over WebSockets and SSE.

Check yourself

  1. 01What is the difference between a query and a subscription in terms of how many results come back?

    A query returns one result and ends. A subscription returns a stream, one result per event, until the client or the server closes it.

  2. 02What do `subscribe` and `resolve` do on a subscription field?

    `subscribe` returns an async iterator that produces the events. `resolve` receives each event and returns the value for the field, and it can be omitted when the event already has the right shape.

  3. 03Why does an in-memory pub/sub stop working when you run two copies of the server?

    A mutation handled by instance A publishes only to subscribers connected to A. Subscribers connected to instance B never hear it, so you need a shared broker such as Redis.

  4. 04When is polling a better choice than a subscription?

    When updates are infrequent or the client can tolerate a delay, since polling needs no open connection and fits ordinary HTTP caching and load balancing.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark