Dispatch makes it easy to work with rate limited or unreliable servers, like the one we’ve prepared for this guide. We’re hosting a server that serves random cat facts, but it’s very unreliable and fails with 500 quite often.
cat-facts.dispatch.run
Imagine our application is critically dependant on that crucial cat knowledge. Normally, we’d have to implement retries on request errors or even push this work into a queue. But with Dispatch, all we have to do is wrap the function with a dispatch.Func call and we’ll fetch our cat facts reliably no matter what.
Let’s see how simple it is to build reliable systems with Dispatch and maybe learn a thing or two about cats.
Setup the development environment
CLI is the fastest way to create a Dispatch account and set up local development environment.
It can be installed via Homebrew:
Or install from sources with Go
Next, log in to create an account:
login command will open a browser to create a Dispatch account, create an API key and save it on your machine.
If you’re starting from scratch, initialize a Go project:
Then install our Go SDK:
Create a basic application
Put Dispatch aside for now and create a simple HTTP server that fetches a cat fact from https://cat-facts.dispatch.run and prints it.
Create an main.go file and paste the following code:
Start the application:
Send a request to / to confirm it’s working:
If it hasn’t failed right away, try sending a few more requests to stumble upon a failure in the cat facts API.
This means that fetchCatFact function raised an exception and now the application is left without a cat fact.
Make the application reliable
Fortunately, Dispatch can be added to make any Go function retry on failure and limit the execution rate.
First, import a Dispatch SDK.
Next, set up a handler that Dispatch will call remotely on your server.
Next, wrap fetchCatFact in a dispatch.Func call, add it to the Dispatch endpoint and update how fetchCatFact is called.
Use the Dispatch method on the fetchCatFact function to call it asynchronously via Dispatch.
Lastly, we need to tell Dispatch that it’s safe to retry fetchCatFact execution when we failed to fetch a cat fact due to API issues.
That’s all it took to make fetchCatFact retry on request errors and asynchronously execute in background.
Restart the application, but this time use Dispatch CLI:
Now, try sending a few more GET / requests to this server and see how failures are automatically retried.
This is the magic of Dispatch. It ensures that fetchCatFact is executed successfully no matter what, whether HTTP requests fail or your server has suddenly rebooted.
Under the hood, when fetchCatFact.Dispatch is called, fetchCatFact is not executed immediately. Instead, Dispatch schedules the execution of fetchCatFact and pings back our server when it’s the time to do so. That way, fetchCatFact is executed asynchronously in background. Whenever a failure happens, Dispatch is notified and retries the execution again.