|
| 1 | +import { Tabs } from 'nextra/components'; |
| 2 | + |
| 3 | +# Server-Side Caching |
| 4 | + |
| 5 | +Cache helpers also provides a simple caching abstraction to be used server-side via `@supabase-cache-helpers/postgrest-server`. |
| 6 | + |
| 7 | +## Motivation |
| 8 | + |
| 9 | +At some point, you might want to cache your PostgREST requests on the server-side too. Most users either do not cache at all, or caching might look like this: |
| 10 | + |
| 11 | + |
| 12 | +```ts |
| 13 | +const cache = new Some3rdPartyCache(...) |
| 14 | + |
| 15 | +let contact = await cache.get(contactId) as Tables<"contact"> | undefined | null; |
| 16 | +if (!contact){ |
| 17 | + const { data } = await supabase.from("contact").select("*").eq("id", contactId).throwOnError() |
| 18 | + contact = data |
| 19 | + await cache.set(contactId, contact, Date.now() + 60_000) |
| 20 | +} |
| 21 | + |
| 22 | +// use contact |
| 23 | +``` |
| 24 | + |
| 25 | +There are a few annoying things about this code: |
| 26 | + |
| 27 | +- Manual type casting |
| 28 | +- No support for stale-while-revalidate |
| 29 | + |
| 30 | +Most people would build a small wrapper around this to make it easier to use and so did we: This library is the result of a rewrite of our own caching layer after some developers were starting to replicate it. It’s used in production by Hellomateo any others. |
| 31 | + |
| 32 | +## Features |
| 33 | + |
| 34 | +- **Typescript**: Fully typesafe |
| 35 | +- **Tiered Cache**: Multiple caches in series to fall back on |
| 36 | +- **Stale-While-Revalidate**: Async loading of data from your origin |
| 37 | +- **Deduping**: Prevents multiple requests for the same data from being made at the same time |
| 38 | + |
| 39 | +## Getting Started |
| 40 | + |
| 41 | +Fist, install the dependency: |
| 42 | + |
| 43 | +<Tabs items={["npm", "pnpm", "yarn", "bun"]}> |
| 44 | + <Tabs.Tab>`npm install @supabase-cache-helpers/postgrest-server`</Tabs.Tab> |
| 45 | + <Tabs.Tab>`pnpm add @supabase-cache-helpers/postgrest-server`</Tabs.Tab> |
| 46 | + <Tabs.Tab>`yarn add @supabase-cache-helpers/postgrest-server`</Tabs.Tab> |
| 47 | + <Tabs.Tab>`bun install @supabase-cache-helpers/postgrest-server`</Tabs.Tab> |
| 48 | +</Tabs> |
| 49 | + |
| 50 | +This is how you can make your first cached query: |
| 51 | + |
| 52 | +```ts |
| 53 | +import { QueryCache } from '@supabase-cache-helpers/postgrest-server'; |
| 54 | +import { MemoryStore } from '@supabase-cache-helpers/postgrest-server/stores'; |
| 55 | +import { createClient } from '@supabase/supabase-js'; |
| 56 | +import { Database } from './types'; |
| 57 | + |
| 58 | +const client = createClient<Database>( |
| 59 | + process.env.SUPABASE_URL, |
| 60 | + process.env.SUPABASE_ANON_KEY |
| 61 | +); |
| 62 | + |
| 63 | +const map = new Map(); |
| 64 | + |
| 65 | +const cache = new QueryCache(ctx, { |
| 66 | + stores: [new MemoryStore({ persistentMap: map })], |
| 67 | + // Configure the defaults |
| 68 | + fresh: 1000, |
| 69 | + stale: 2000, |
| 70 | +}); |
| 71 | + |
| 72 | +const res = await cache.query( |
| 73 | + client |
| 74 | + .from('contact') |
| 75 | + .select('id,username') |
| 76 | + .eq('username', contacts[0].username!) |
| 77 | + .single(), |
| 78 | + // overwrite the default per query |
| 79 | + { fresh: 100, stale : 200 } |
| 80 | +); |
| 81 | + |
| 82 | +``` |
| 83 | + |
| 84 | +### Context |
| 85 | + |
| 86 | +You may wonder what `ctx` is passed above. In serverless functions it’s not always trivial to run some code after you have returned a response. This is where the context comes in. It allows you to register promises that should be awaited before the function is considered done. Fortunately many providers offer a way to do this. |
| 87 | + |
| 88 | +In order to be used in this cache library, the context must implement the following interface: |
| 89 | + |
| 90 | +```ts |
| 91 | +export interface Context { |
| 92 | + waitUntil: (p: Promise<unknown>) => void; |
| 93 | +} |
| 94 | +``` |
| 95 | + |
| 96 | +For stateful applications, you can use the `DefaultStatefulContext`: |
| 97 | + |
| 98 | +```ts |
| 99 | +import { DefaultStatefulContext } from "@unkey/cache"; |
| 100 | +const ctx = new DefaultStatefulContext() |
| 101 | +``` |
| 102 | + |
| 103 | +## Tiered Cache |
| 104 | + |
| 105 | +Different caches have different characteristics, some may be fast but volatile, others may be slow but persistent. By using a tiered cache, you can combine the best of both worlds. In almost every case, you want to use a fast in-memory cache as the first tier. There is no reason not to use it, as it doesn’t add any latency to your application. |
| 106 | + |
| 107 | +The goal of this implementation is that it’s invisible to the user. Everything behaves like a single cache. You can add as many tiers as you want. |
| 108 | + |
| 109 | +### Example |
| 110 | + |
| 111 | +```ts |
| 112 | +import { QueryCache } from '@supabase-cache-helpers/postgrest-server'; |
| 113 | +import { MemoryStore, RedisStore } from '@supabase-cache-helpers/postgrest-server/stores'; |
| 114 | +import { Redis } from 'ioredis'; |
| 115 | +import { createClient } from '@supabase/supabase-js'; |
| 116 | +import { Database } from './types'; |
| 117 | + |
| 118 | +const client = createClient<Database>( |
| 119 | + process.env.SUPABASE_URL, |
| 120 | + process.env.SUPABASE_ANON_KEY |
| 121 | +); |
| 122 | + |
| 123 | +const map = new Map(); |
| 124 | + |
| 125 | +const redis = new Redis({...}); |
| 126 | + |
| 127 | +const cache = new QueryCache(ctx, { |
| 128 | + stores: [new MemoryStore({ persistentMap: map }), new RedisStore({ redis })], |
| 129 | + fresh: 1000, |
| 130 | + stale: 2000 |
| 131 | +}); |
| 132 | + |
| 133 | +const res = await cache.query( |
| 134 | + client |
| 135 | + .from('contact') |
| 136 | + .select('id,username') |
| 137 | + .eq('username', contacts[0].username!) |
| 138 | + .single() |
| 139 | +); |
| 140 | + |
| 141 | +``` |
| 142 | + |
| 143 | + |
| 144 | +## Stale-While-Revalidate |
| 145 | + |
| 146 | +To make data fetching as easy as possible, the cache offers a swr method, that acts as a pull through cache. If the data is fresh, it will be returned from the cache, if it’s stale it will be returned from the cache and a background refresh will be triggered and if it’s not in the cache, the data will be synchronously fetched from the origin. |
| 147 | + |
| 148 | +```ts |
| 149 | +const res = await cache.swr( |
| 150 | + client |
| 151 | + .from('contact') |
| 152 | + .select('id,username') |
| 153 | + .eq('username', contacts[0].username!) |
| 154 | + .single() |
| 155 | +); |
| 156 | +``` |
| 157 | + |
0 commit comments