Real-Time Communication with GraphQL Subscriptions — A Trading app sample

Building real-time communication with GraphQL Subscriptions and golang

PRATHEESH PC
5 min readDec 15, 2023

The world of web applications is constantly evolving, and real-time communication is becoming increasingly crucial for creating immersive and engaging experiences. While traditional REST APIs deliver data on demand, they lack the immediacy and dynamism needed for seamless interaction. This is where GraphQL subscriptions come to the rescue, offering a powerful tool for pushing data updates directly to clients as they occur.

GraphQL subscriptions are a feature that allows clients to receive real-time updates from a server when specific events or changes occur. Unlike regular GraphQL queries or mutations that fetch or modify data once, subscriptions create a persistent connection between the client and server, enabling a continuous stream of data

See the sample code

What is GraphQL?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It essentially gives developers and users more control over the data they fetch from an API compared to traditional REST APIs.

Benefits

  • Increased flexibility and control: You only fetch the data you need, reducing unnecessary data transfer and improving performance.
  • Improved developer experience: Writing specific queries makes code more concise and easier to maintain.
  • Reduced server load: By fetching only what’s needed, you reduce the burden on your back-end servers.
  • Stronger data consistency: GraphQL schema defines data structure, leading to more consistent and predictable responses.
  • Evolving capabilities: Features like subscriptions enable real-time data updates, expanding the possibilities of your application.

Compared to REST APIs

  • REST: You make pre-defined requests to specific endpoints, often receiving more data than you need.
  • GraphQL: You write queries that specify the exact data you want, reducing unnecessary data transfer.

Components of Graphql

Schema

  • Types: These define the structure of your data, including objects, interfaces, enums, and scalar types.
  • Fields: These are specific properties within a type that can be queried or mutated.
  • Directives: These provide instructions on how to process or handle fields and operations.

Server Side

  • Resolvers: These functions handle fetching data from your data sources based on incoming queries and mutations.
  • Middleware: These functions intercept and modify queries and mutations before they reach the resolvers, allowing for authorization, error handling, and other logic.
  • Data Sources: These are the physical locations where your data resides, such as databases, APIs, or other systems.

Client Side

  • Queries: These are requests to fetch data from your GraphQL API. They specify the exact data you need, including which fields you want to retrieve from specific types. For example, a query might request the name and age of a user with a specific ID.
  • Mutations: These are used to modify data on your server. They define what data you want to change and how to change it. For example, a mutation might update a user’s email address or create a new post.
  • Subscriptions: These enable real-time data updates. You can subscribe to changes in specific data on your server and receive notifications whenever those changes occur. For example, you could subscribe to new messages in a chatroom and receive them instantly as they are posted.
react sample trade application screenshot

So, now you got some basic idea about the graphql. Now let’s build a live trading application sample with graphql + golang + react

Setup dependencies

github.com/graphql-go/graphqlpackage is a popular choice for the graphql implementation in golang.

go get github.com/graphql-go/graphql

Directory structure

gqlgen.yml

gqlgen.yml file is a configuration file used by the gengql package in Golang. It helps you customize the code generation process for your GraphQL API based on your specific needs.

Defining the Graphql schema

Schema is a critical component of GraphQL. It defines the structure of the data available via a GraphQL API, specifying the types of data that can be queried and how they relate to each other.

Generate the resolvers

Now you can run go run github.com/99designs/gqlgen to generate the codes. After this it will create schema.resolvers.go, generated.go and model_gen.go

And we should have resolver method as follows.

// Trade is the resolver for the trade field.
func (r *queryResolver) Trade(ctx context.Context) ([]*model.TradeData, error) {
panic(fmt.Errorf("not implemented: Trade - Trade"))
}

// LiveTrade is the resolver for the liveTrade field.
func (r *subscriptionResolver) LiveTrade(ctx context.Context, symbol string) (<-chan *model.TradeData, error) {
panic(fmt.Errorf("not implemented: LiveTrade - LiveTrade"))
}

Implement the resolver

The subscription is implemented in the LiveTrade subscription resolver. When a client starts a subscription, the server assigns it a unique identification and opens a Go channel for future data updates. In the code it will send some sample data to the channel on every 1 second interval. All the clients need to know is that they will receive a portion of the trades that are accessible on the WebSocket subscription that they created.

Implement server.go

We put up the graphql backend server. We must now link it from a client and get the real-time data updates. Let’s give it a go with react and the Appolo client. You can setup a react app and install the appolo client

npm install @apollo/client graphql

useSubscription is a React hook provided by Apollo Client for managing GraphQL subscriptions.

data: Will contain the received live trade information fetched by the subscription and we can render it in the pages.

Finally

Start the server

Start the client

Conclusion

In conclusion, GraphQL subscriptions introduce a powerful real-time data exchange mechanism, transforming the way clients interact with servers. By enabling a persistent connection between the server and subscribed clients, subscriptions facilitate live data updates and notifications.

I hope this article helps. Thank you so much for reading. :)

Here you can get the entire code

Learn More about

Enjoy learning

--

--

PRATHEESH PC

Hey there! I'm a software developer and I'm absolutely in love with building things with technology.