Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Clients and Transport

Subscriptions, Live Updates and File Uploads

Compare subscriptions, polling and live queries, learn pub/sub topics and event filtering, and see why file uploads usually happen outside GraphQL.

Most of GraphQL is request and response: the client asks, the server answers, and the connection is done. Many products also need the server to tell the client when something changes: a new chat message, a price tick, a finished export. And almost every product eventually needs to accept files, which JSON does not handle well.

This lesson covers both. You met the syntax of subscriptions in Mutations and Subscriptions and the transports in GraphQL over HTTP. Here you learn when to use them, how a server routes events, and what to do about uploads. No subscription server runs on this site, so real server code is read-only. The runnable example is a stand-in pub/sub in Node: a topic registry with filtering, which is the logic inside most subscription resolvers.

Three ways to stay fresh

Polling Ask again every few seconds.
Subscription The server pushes each event.
Live query The server re-runs a query on change.

Start with polling. Upgrade when it hurts.

1 / 2

Polling, subscriptions and live queries

Polling means re-running a normal query on a timer. It needs no new infrastructure, works with caching and CDNs, and fails gracefully. Its cost is wasted requests and a delay of up to one interval. For a dashboard that updates every 30 seconds, it is the right answer.

Subscriptions keep a connection open (WebSocket or Server-Sent Events) and push a result per event. They give low latency and no wasted requests, but each client holds a connection, so you must plan for thousands of open sockets, authentication at connect time, reconnection, and fan-out across several servers.

Live queries are a less standard idea: the server re-runs a whole query whenever the data it read changes, and sends the new result. They are convenient for the client but hard to build, and support is limited to certain servers. Treat them as an advanced option.

A rule of thumb:

  • Data changes rarely, or a delay is fine: poll.
  • Events are small and discrete (a message arrived): subscribe.
  • Users need an always-correct view of complex data: subscribe to events and update the client cache, or refetch the query when an event arrives.

A very common hybrid: the subscription sends a tiny "something changed" event, and the client refetches the query. It keeps the subscription simple and the data authoritative.

Pub/sub and topics

Behind a subscription there is usually a publish/subscribe system. A mutation (or a background job) publishes an event to a topic, and every subscription resolver listening on that topic receives it. Topics are plain strings, such as MESSAGE_ADDED or room:42:messages.

A read-only sketch, in the shape most Node servers use:

JavaScript
const resolvers = {
  Mutation: {
    async sendMessage(_, { input }, { user, pubsub, db }) {
      const message = await db.messages.insert({ ...input, authorId: user.id });
      await pubsub.publish("room:" + input.roomId, { messageAdded: message });
      return { message };
    },
  },
  Subscription: {
    messageAdded: {
      subscribe: (_, { roomId }, { pubsub, user }) => {
        // authorize at subscribe time
        return pubsub.asyncIterator("room:" + roomId);
      },
    },
  },
};

Two design points matter in production:

  1. The in-memory pub/sub of the tutorial examples works for one server process only. With several servers, you need a shared broker such as Redis or a message queue, so an event published on server A reaches clients connected to server B.
  2. Authorize when the subscription starts, and again for sensitive events. A client that subscribes to someone else's room must be refused, just like a query (see Authentication and Authorization).

Filtering events

Often many clients listen to the same topic but each wants only some events: messages for one room, orders above a value, updates for one product. Put the filter on the server. Sending everything and filtering in the browser wastes bandwidth and can leak data the user must not see.

You can filter in two ways:

  • Narrow topics: publish to room:42, so only that room's subscribers get the event.
  • Filter functions: all events go to a broad topic, and each subscription carries a predicate that decides whether to deliver.

The stand-in below implements both ideas in a few lines. Each subscriber registers a topic, an optional filter and a selection (the fields it wants), the same pattern you saw in the earlier stand-in.

Node.js A stand-in pub/sub with topics and filters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the counts: the first message reaches Alice's client and the audit listener, the second reaches Bob and the audit listener, and after stopAudit() only Alice receives the third. Always clean up when a client disconnects, or the server leaks memory and keeps doing work for nobody.

Why uploads are tricky in GraphQL

GraphQL variables are JSON, and JSON has no binary type. You could base64-encode a file into a string, but that inflates its size by about a third and loads the whole file into memory in the server. Two real approaches exist.

The multipart request convention

A community specification ("GraphQL multipart request") sends a multipart/form-data request with three parts: an operations JSON field (with null where the file goes), a map that says which file fills which variable, and the file parts. Many server libraries support it with an Upload scalar. A read-only schema and request:

GRAPHQL
scalar Upload

type Mutation {
  uploadAvatar(file: Upload!): UploadResult!
}
Terminal
curl https://api.example.com/graphql \
  -F operations='{ "query": "mutation ($file: Upload!) { uploadAvatar(file: $file) { url } }", "variables": { "file": null } }' \
  -F map='{ "0": ["variables.file"] }' \
  -F 0[email protected]

It is convenient, but the file flows through your GraphQL server, which complicates size limits and CSRF protection (browsers can send multipart forms cross-site), and ties up server memory and workers.

Signed URLs (usually better)

The common production pattern keeps files outside GraphQL:

  1. The client calls a mutation such as requestUpload(filename, contentType, size).
  2. The server checks permissions and limits, and returns a pre-signed URL to object storage (for example S3-compatible storage) plus a file ID.
  3. The client uploads the bytes directly to storage with a plain PUT.
  4. The client calls completeUpload(id) (or storage notifies the server), and the server links the file to the record.
sequenceDiagram
    participant C as Client
    participant G as GraphQL API
    participant S as Object storage
    C->>G: mutation requestUpload
    G-->>C: signed URL and file ID
    C->>S: PUT file bytes
    S-->>C: 200 OK
    C->>G: mutation completeUpload
    G-->>C: file record

The GraphQL API handles only small JSON messages; the large bytes go straight to storage.

This scales better, supports resumable and large uploads, and keeps the GraphQL server fast. The stand-in below simulates the two GraphQL steps, with a signed token that expires.

Node.js A stand-in signed-upload flow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The storage service in this stand-in only checks the signature and expiry, which is the same trick real signed URLs use. In production, use your storage provider's own signing feature rather than rolling your own.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A dashboard needs fresh data once a minute. What is usually the simplest good choice?

    Polling needs no new infrastructure and works with caches. Subscriptions are worth their cost when low latency matters.
  2. 2. Why is an in-memory pub/sub not enough with three server instances?

    Each process has its own memory. Use a shared broker such as Redis so events reach every instance.
  3. 3. Where should event filtering happen?

    Server-side filtering saves bandwidth and prevents leaking events the user must not see.
  4. 4. What is the main advantage of signed-URL uploads over sending files through GraphQL?

    The API only exchanges small JSON messages while storage receives the bytes directly. It also simplifies size limits and resumable uploads.

Summary

  • Poll when freshness needs are modest; subscribe for discrete low-latency events; live queries are advanced and less common.
  • Subscriptions are usually backed by pub/sub topics; production needs a shared broker across servers.
  • Authorize on subscribe, filter on the server, and clean up on disconnect.
  • JSON cannot carry files; the multipart convention works but routes bytes through your API.
  • Signed URLs keep large uploads outside GraphQL and are the usual production choice.
  • The pub/sub and signed-URL code here are stand-ins; real servers use a broker and your storage provider's signing.

Next: Testing GraphQL APIs.