Temporal promises to help you build invincible apps. To make this possible, new design patterns are introduced that are very different from the ones used in a traditional web app architecture.
Instead of letting your API endpoints talk to a database over the network, they would instead call in-memory Workflows that store state internally. Temporal handles persisting the state of your Workflows and distributes your Workflow between Workers as necessary. You, as the developer are responsible for implementing Workflows and Activities as normal Go code. Meanwhile, Temporal handles the data persistence and horizontal scaling for you.
In this blog post, I'll demonstrate how to build a shopping cart using long-living Workflows. You can find the full source code for this shopping cart on GitHub.
In a traditional web app architecture, a user's shopping cart is stored as a row or document in a database. While you can store shopping carts in a separate database using Temporal, you have another option: you can represent a shopping cart as a long-living Workflow.
A Workflow is a Go function that takes 2 parameters: a Temporal Workflow context
ctx and an arbitrary
It can run for an arbitrarily long period of time, as Temporal can handle pausing and restarting the Workflow.
Lastly, it is able to share its state via queries and modify its state in response to signals.
The following is a simplified shopping cart that adds a new product to the cart every time it receives an
To run a Workflow, you need to create a Worker process.
A Temporal Worker listens for events on a queue and has a list of registered Workflows that it can run in response to messages on the queue.
Below is the largely-boilerplate
In order to see this shopping cart Workflow in action, you can create a starter that sends queries and signals to modify the shopping cart.
In order to support adding and removing elements from the cart, the Workflow needs to respond to different types of signals. Signals are a way to notify Workflows of external events. The following code listens to a Signal channel for messages that either add or remove items from a shopping cart.
RemoveFromCart() functions need to do is modify the
Temporal is responsible for persisting and distributing
Temporal introduces a new way of building web applications; instead of storing a shopping cart in a database, you can represent a shopping cart as a long-living Workflow. For simple CRUD applications like this shopping cart app, this pattern doesn't really make things significantly easier. In the next post, we'll look at a case where Temporal's long-living Workflows shine: sending a reminder email if the user abandons their cart.
Update: You can now find Part 2 here!