Skip to content

Commit e31fb52

Browse files
grdsdevclaude
authored andcommitted
feat(postgrest): add automatic retries for transient errors
Implement automatic retry logic for PostgREST SDK requests that fail with 520 status codes (Cloudflare timeout/connection errors). Key features: - Enabled by default for GET/HEAD/OPTIONS requests - 3 retry attempts with exponential backoff (1s, 2s, 4s) - X-Retry-Count header sent for observability - Can be disabled globally or per-request via .retry(false) This addresses customer feedback about perceived reliability issues when transient 520 errors occur under load. Related: https://linear.app/supabase/project/automatic-retries-for-postgrest-sdk-c6fa4eaf163a Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent f26b924 commit e31fb52

7 files changed

Lines changed: 647 additions & 60 deletions

File tree

‎packages/core/postgrest-js/src/PostgrestBuilder.ts‎

Lines changed: 223 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,51 @@ import type {
55
MergePartialResult,
66
IsValidResultOverride,
77
} from './types/types'
8-
import { ClientServerOptions, Fetch } from './types/common/common'
8+
import {
9+
ClientServerOptions,
10+
Fetch,
11+
DEFAULT_MAX_RETRIES,
12+
getRetryDelay,
13+
RETRYABLE_STATUS_CODES,
14+
RETRYABLE_METHODS,
15+
} from './types/common/common'
916
import PostgrestError from './PostgrestError'
1017
import { ContainsNull } from './select-query-parser/types'
1118

19+
/**
20+
* Sleep for a given number of milliseconds.
21+
*/
22+
function sleep(ms: number): Promise<void> {
23+
return new Promise((resolve) => setTimeout(resolve, ms))
24+
}
25+
26+
/**
27+
* Check if a request should be retried based on method and status code.
28+
*/
29+
function shouldRetry(
30+
method: string,
31+
status: number,
32+
attemptCount: number,
33+
retryEnabled: boolean
34+
): boolean {
35+
// Don't retry if retries are disabled or we've exhausted attempts
36+
if (!retryEnabled || attemptCount >= DEFAULT_MAX_RETRIES) {
37+
return false
38+
}
39+
40+
// Only retry idempotent methods (GET, HEAD, OPTIONS)
41+
if (!RETRYABLE_METHODS.includes(method as (typeof RETRYABLE_METHODS)[number])) {
42+
return false
43+
}
44+
45+
// Only retry on specific status codes (520 - Cloudflare errors)
46+
if (!RETRYABLE_STATUS_CODES.includes(status as (typeof RETRYABLE_STATUS_CODES)[number])) {
47+
return false
48+
}
49+
50+
return true
51+
}
52+
1253
export default abstract class PostgrestBuilder<
1354
ClientOptions extends ClientServerOptions,
1455
Result,
@@ -29,6 +70,9 @@ export default abstract class PostgrestBuilder<
2970
protected isMaybeSingle: boolean
3071
protected urlLengthLimit: number
3172

73+
// Retry configuration - enabled by default
74+
protected retryEnabled: boolean = true
75+
3276
/**
3377
* Creates a builder configured for a specific PostgREST request.
3478
*
@@ -65,6 +109,8 @@ export default abstract class PostgrestBuilder<
65109
fetch?: Fetch
66110
isMaybeSingle?: boolean
67111
urlLengthLimit?: number
112+
// Retry option
113+
retry?: boolean
68114
}) {
69115
this.method = builder.method
70116
this.url = builder.url
@@ -75,6 +121,7 @@ export default abstract class PostgrestBuilder<
75121
this.signal = builder.signal
76122
this.isMaybeSingle = builder.isMaybeSingle ?? false
77123
this.urlLengthLimit = builder.urlLengthLimit ?? 8000
124+
this.retryEnabled = builder.retry ?? true
78125

79126
if (builder.fetch) {
80127
this.fetch = builder.fetch
@@ -110,6 +157,29 @@ export default abstract class PostgrestBuilder<
110157
/** *
111158
* @category Database
112159
*/
160+
/**
161+
* Configure retry behavior for this request.
162+
*
163+
* By default, retries are enabled for GET/HEAD requests that fail with
164+
* 520 status codes (Cloudflare timeout/connection errors). Retries use
165+
* exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts.
166+
*
167+
* @param enabled - Whether to enable retries for this request
168+
*
169+
* @example
170+
* ```ts
171+
* // Disable retries for a specific query
172+
* const { data, error } = await supabase
173+
* .from('users')
174+
* .select()
175+
* .retry(false)
176+
* ```
177+
*/
178+
retry(enabled: boolean): this {
179+
this.retryEnabled = enabled
180+
return this
181+
}
182+
113183
then<
114184
TResult1 = ThrowOnError extends true
115185
? PostgrestResponseSuccess<Result>
@@ -141,39 +211,22 @@ export default abstract class PostgrestBuilder<
141211
// NOTE: Invoke w/o `this` to avoid illegal invocation error.
142212
// https://github.com/supabase/postgrest-js/pull/247
143213
const _fetch = this.fetch
144-
let res = _fetch(this.url.toString(), {
145-
method: this.method,
146-
headers: this.headers,
147-
body: JSON.stringify(this.body),
148-
signal: this.signal,
149-
}).then(async (res) => {
150-
let error = null
151-
let data = null
152-
let count: number | null = null
153-
let status = res.status
154-
let statusText = res.statusText
155-
156-
if (res.ok) {
157-
if (this.method !== 'HEAD') {
158-
const body = await res.text()
159-
if (body === '') {
160-
// Prefer: return=minimal
161-
} else if (this.headers.get('Accept') === 'text/csv') {
162-
data = body
163-
} else if (
164-
this.headers.get('Accept') &&
165-
this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text')
166-
) {
167-
data = body
168-
} else {
169-
data = JSON.parse(body)
170-
}
171-
}
172214

173-
const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/)
174-
const contentRange = res.headers.get('content-range')?.split('/')
175-
if (countHeader && contentRange && contentRange.length > 1) {
176-
count = parseInt(contentRange[1])
215+
// Execute fetch with retry logic
216+
const executeWithRetry = async (): Promise<{
217+
error: any
218+
data: any
219+
count: number | null
220+
status: number
221+
statusText: string
222+
}> => {
223+
let attemptCount = 0
224+
225+
while (true) {
226+
// Clone headers for each attempt and add retry count header if this is a retry
227+
const requestHeaders = new Headers(this.headers)
228+
if (attemptCount > 0) {
229+
requestHeaders.set('X-Retry-Count', String(attemptCount))
177230
}
178231

179232
// Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods.
@@ -200,42 +253,47 @@ export default abstract class PostgrestBuilder<
200253
const body = await res.text()
201254

202255
try {
203-
error = JSON.parse(body)
204-
205-
// Workaround for https://github.com/supabase/postgrest-js/issues/295
206-
if (Array.isArray(error) && res.status === 404) {
207-
data = []
208-
error = null
209-
status = 200
210-
statusText = 'OK'
256+
const res = await _fetch(this.url.toString(), {
257+
method: this.method,
258+
headers: requestHeaders,
259+
body: JSON.stringify(this.body),
260+
signal: this.signal,
261+
})
262+
263+
// Check if we should retry this response
264+
if (shouldRetry(this.method, res.status, attemptCount, this.retryEnabled)) {
265+
const delay = getRetryDelay(attemptCount)
266+
attemptCount++
267+
await sleep(delay)
268+
continue
211269
}
212-
} catch {
213-
// Workaround for https://github.com/supabase/postgrest-js/issues/295
214-
if (res.status === 404 && body === '') {
215-
status = 204
216-
statusText = 'No Content'
217-
} else {
218-
error = {
219-
message: body,
220-
}
270+
271+
// Process successful or final response
272+
return await this.processResponse(res)
273+
} catch (fetchError: any) {
274+
// Don't retry network errors for non-idempotent methods
275+
if (!RETRYABLE_METHODS.includes(this.method as (typeof RETRYABLE_METHODS)[number])) {
276+
throw fetchError
221277
}
222-
}
223278

224279
if (error && this.shouldThrowOnError) {
225280
throw new PostgrestError(error)
281+
// Check if we should retry network errors
282+
if (this.retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) {
283+
const delay = getRetryDelay(attemptCount)
284+
attemptCount++
285+
await sleep(delay)
286+
continue
287+
}
288+
289+
// Exhausted retries or retries disabled, throw the last error
290+
throw fetchError
226291
}
227292
}
293+
}
228294

229-
const postgrestResponse = {
230-
error,
231-
data,
232-
count,
233-
status,
234-
statusText,
235-
}
295+
let res = executeWithRetry()
236296

237-
return postgrestResponse
238-
})
239297
if (!this.shouldThrowOnError) {
240298
res = res.catch((fetchError) => {
241299
// Build detailed error information including cause if available
@@ -307,6 +365,111 @@ export default abstract class PostgrestBuilder<
307365
return res.then(onfulfilled, onrejected)
308366
}
309367

368+
/**
369+
* Process a fetch response and return the standardized postgrest response.
370+
*/
371+
private async processResponse(res: Response): Promise<{
372+
error: any
373+
data: any
374+
count: number | null
375+
status: number
376+
statusText: string
377+
}> {
378+
let error = null
379+
let data = null
380+
let count: number | null = null
381+
let status = res.status
382+
let statusText = res.statusText
383+
384+
if (res.ok) {
385+
if (this.method !== 'HEAD') {
386+
const body = await res.text()
387+
if (body === '') {
388+
// Prefer: return=minimal
389+
} else if (this.headers.get('Accept') === 'text/csv') {
390+
data = body
391+
} else if (
392+
this.headers.get('Accept') &&
393+
this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text')
394+
) {
395+
data = body
396+
} else {
397+
data = JSON.parse(body)
398+
}
399+
}
400+
401+
const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/)
402+
const contentRange = res.headers.get('content-range')?.split('/')
403+
if (countHeader && contentRange && contentRange.length > 1) {
404+
count = parseInt(contentRange[1])
405+
}
406+
407+
// Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361
408+
// Issue persists e.g. for `.insert([...]).select().maybeSingle()`
409+
if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) {
410+
if (data.length > 1) {
411+
error = {
412+
// https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553
413+
code: 'PGRST116',
414+
details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,
415+
hint: null,
416+
message: 'JSON object requested, multiple (or no) rows returned',
417+
}
418+
data = null
419+
count = null
420+
status = 406
421+
statusText = 'Not Acceptable'
422+
} else if (data.length === 1) {
423+
data = data[0]
424+
} else {
425+
data = null
426+
}
427+
}
428+
} else {
429+
const body = await res.text()
430+
431+
try {
432+
error = JSON.parse(body)
433+
434+
// Workaround for https://github.com/supabase/postgrest-js/issues/295
435+
if (Array.isArray(error) && res.status === 404) {
436+
data = []
437+
error = null
438+
status = 200
439+
statusText = 'OK'
440+
}
441+
} catch {
442+
// Workaround for https://github.com/supabase/postgrest-js/issues/295
443+
if (res.status === 404 && body === '') {
444+
status = 204
445+
statusText = 'No Content'
446+
} else {
447+
error = {
448+
message: body,
449+
}
450+
}
451+
}
452+
453+
if (error && this.isMaybeSingle && error?.details?.includes('0 rows')) {
454+
error = null
455+
status = 200
456+
statusText = 'OK'
457+
}
458+
459+
if (error && this.shouldThrowOnError) {
460+
throw new PostgrestError(error)
461+
}
462+
}
463+
464+
return {
465+
error,
466+
data,
467+
count,
468+
status,
469+
statusText,
470+
}
471+
}
472+
310473
/**
311474
* Override the type of the returned `data`.
312475
*

0 commit comments

Comments
 (0)