Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active February 5, 2021 18:00
Show Gist options
  • Save andyrichardson/624e243d41995b18c9730e1547bad6e7 to your computer and use it in GitHub Desktop.
Save andyrichardson/624e243d41995b18c9730e1547bad6e7 to your computer and use it in GitHub Desktop.

Websocket vs Subscriptions

What is a websocket

Websockets create a sustained connection between a client and a server

Messages can be sent on this connection in either direction.

It is a transport protocol.

What is GraphQL (bare with me)

GraphQL is a query language.

The GraphQL spec does not dictate a transport protocol. This means you can send GraphQL queries via HTTP, WebSocket or pidgeon mail if you really want to.

Notee: In urql, we even have a plugin to execute queries without any transport at all (using a schema on the client side).

What are subscriptions

Subscriptions are a mechanism in GraphQL spec indended for sending data using a sustained connection.

What is the relationship between Subscriptions and Websockets?

Just like how we send GraphQL (query language) request's over HTTP/S (transport protocol), with subscriptions, we can send GraphQL (query language) subscriptions over WebSocket (transport protocol).

Handling subscriptions in serverless

DISCLAIMER: IF YOU HAVEN'T READ THE ABOVE, NOW IS YOUR LAST CHANCE

Okay so transport protocol aside, there are three different messages from graphql-ws we care about.

Messages from the client

connection_init

This is the first message we get from the client.

We persist the contents of this message as it contains headers which could be used later.

See here for the init handler

subscribe (start)

This is a message requesting the start of a subscription (with query, variables, and sub id)

We persist the contents of this message so we can keep track of subscribers and pass the arguments to resolvers later in the case of an event

See here for subscribe handler

complete (stop)

This is a message requesting the termination of a subscription (with sub id)

We remove the subscription from our persistence layer if this is called.

See here for complete handler

Socket events

Disconnect

When a socket is closed, subscriptions are no longer active.

We remove all persisted data from that socket (connection) in the case of a socket close.

See here for disconnect handler

Lambda events

NEW_ORDER

When the lambda is called with a new_order event, we go to the persistence layer to find all subscribers of that event.

Following this, we execute their subscription with the new event before sending the result to those subscribed clients.

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