From bf814b4833d3d8a8a9c6ef493600adb66463ba4a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 2 Jan 2024 11:42:22 -0600 Subject: [PATCH] Add Exit Function Early Without Retries as an Inngest TIL --- README.md | 7 ++- .../exit-function-early-without-retries.md | 44 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 inngest/exit-function-early-without-retries.md diff --git a/README.md b/README.md index 8c1bb3c..4bccbbd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1361 TILs and counting..._ +_1362 TILs and counting..._ --- @@ -33,6 +33,7 @@ _1361 TILs and counting..._ * [Heroku](#heroku) * [HTML](#html) * [HTTP](#http) +* [Inngest](#inngest) * [Internet](#internet) * [JavaScript](#javascript) * [jq](#jq) @@ -389,6 +390,10 @@ _1361 TILs and counting..._ - [What Counts As Cross-Origin With CORS?](http/what-counts-as-cross-origin-with-cors.md) +### Inngest + +- [Exit Function Early Without Retries](inngest/exit-function-early-without-retries.md) + ### Internet - [Add Emoji To GitHub Repository Description](internet/add-emoji-to-github-repository-description.md) diff --git a/inngest/exit-function-early-without-retries.md b/inngest/exit-function-early-without-retries.md new file mode 100644 index 0000000..7482e16 --- /dev/null +++ b/inngest/exit-function-early-without-retries.md @@ -0,0 +1,44 @@ +# Exit Function Early Without Retries + +When an Inngest function fails due to an error, it will be retried up to 3 +times with a scheduled back-off. That functionality is built-in. In some cases, +there is no sense retrying because the failure case isn't going to change. No +sense in wasting resources on retries that are going to yield the same result. + +In this case, we can have our code raise a `NonRetriableError`. + +```javascript +import { NonRetriableError } from "inngest" +import {inngest} from '@/inngest/inngest.server' +import {database} from '@/server/database' + +export default inngest.createFunction( + { id: "reindex-post-for-search" }, + { event: "post.updated" }, + async ({ event }) => { + const post = await database.findPost({ id: event.data.postId }) + + if(!post) { + throw new NonRetriableError(`Post not found for id (${event.data.postId})`) + } + + // handle reindexing of the post + } +) +``` + +When inngest catches a `NonRetriableError` it knows to not schedule retries. + +In the context of a try/catch block where some other error has been raised, we +can pass that error as a second argument to the `NonRetriableError` for +additional info: + +```javascript +catch(err) { + const message = `Post not found for id (${event.data.postId})` + + throw new NonRetriableError(message, { cause: err }) +} +``` + +[source](https://www.inngest.com/docs/functions/retries)