Up until now we talked about queries to fetch data and mutations to update data, but there is a third way: subscriptions. Subscriptions are used to be notified of events such as the creation of a new thing or the changing of the value of a variable.

How do subscriptions work

Queries and mutations work via HTTP requests, that is the client sends a request and the server responds; subscriptions work via WebSockets instead, that is a communication channel is kept open between client and server, this way when an event is triggered the server can send it directly to the client.
Don’t worry: you don’t have to know how WebSockets work in order to use the subscriptions, the key takeaway is that with WebSockets the server can send data whenever it wants, whereas with HTTP requests the server can only respond to a client’s request.
You can do some experiments with subscriptions in the playground, the syntax is the same as for queries and mutations, but when running the subscription instead of receiving a response the playground will show you every event that is sent to you from the server.

subscription {
  thingCreated {
    id
    name
  }
}
An example use case

You are building a smart door lock, you have a boolean variable that the user can update to open or close the lock at any time through Aurora.
Your thing needs to know when the open/closed value changes to act accordingly, you can do it in 2 ways:

  • if you were to use queries to do this you would have to send a request to the server every second or so to check the value, you would make an enormous amount of useless requests, because the value will change only a few times a day, and you would still have a 1 second latency
  • on the other hand you can use a subscription to be notified when the value changes, no data is sent when the user does not change the value and the only latency is the thing’s internet connection
How do I use a subscription?

The easiest way to use a subscription is through our libraries, but if you are using an unsupported language you still have 2 options:

  • use a generic GraphQL library and write the subscription yourself, like you would do in the playground
  • use a generic WebSocket library and send the messages to the server yourself, this is easier than it sounds, you can read more in our guide here