Hasura makes it easy to integrate business logic into your GraphQL API with an eventing system called Actions.
- How you set it up
- How it works
- End-to-end architecture
- Related architectures / patterns
- Use-cases & Benefits
- Try it out
How you set it up
- Build an event handler (an API, a serverless function, a Postgres function)
- Attach a mutation spec and optionally configure relationships to connect the output of the event handler to the rest of the "graph", that Hasura will enrich automatically
How it works
1) GraphQL mutation → Event
Hasura receives the GraphQL mutation and converts this request into an event payload.
2) Event captured → Persisted → Event delivered
The event is captured, persisted and then delivered to the handler with the appropriate retry/delivery guarantees. The event handler can be an API endpoint, a serverless function or even a Postgres function!
3) Event handler runs → Event response
The event handler runs and returns a response that is captured as an event and again persisted to the event store.
4a) Sync mode: Event response → Enrich → GraphQL mutation response
In "sync" mode, the GraphQL client is not aware of the event driven flow and gets the appropriate response within the GraphQL mutation response fields.
4b) Async mode: Event response → Enrich → GraphQL subscription
In "async" mode, the GraphQL client can subscribe to the results of the action, and get an updated result when the event response is available!
End-to-end GraphQL architecture with Actions
We thought about Actions inspired from a one-way data flow architecture. In this pattern, the "write models" are separate from "read models". Instead of CRUD on resources, an architecture leveraging actions would be more similar to CQRS or to a redux like flow! More details about how this relates to other architectures in the next section.
This is what an end to end GraphQL architecture using Hasura Actions would look like:
Use-cases & Benefits
Actions in Hasura bring several benefits to your backend workflow:
- Build event-driven backends without the operational and setup effort
- Event handlers can be completely independent (microservices, serverless functions) and need not care about GraphQL types, schemas and relationships
- API consumers get convenient GraphQL mutations which can reference the entire graph
- Switch between sync & async modes depending on what is best for the API consumer without burdening the authors of the event handler
Related Architectures & Patterns
We've built a simple food ordering app that uses a Actions to create and end-to-end async workflow. Actions fits into the 3factor architecture as the eventing plumbing to drive business logic easily!
- Try out the app here: https://serverless-demo.hasura.app/order-app/
- Watch a demo highlighting scalability and fault-tolerance benefits of having event-based backend: https://www.youtube.com/watch?v=Kd72MM39W1U