Skip to content

perf: store the md5 etag in an xattr instead of hashing on every read - #1771

Open
Heman10x-NGU wants to merge 1 commit into
supabase:masterfrom
Heman10x-NGU:perf/file-backend-md5-etag-cache
Open

Heman10x-NGU wants to merge 1 commit into
supabase:masterfrom
Heman10x-NGU:perf/file-backend-md5-etag-cache

Conversation

@Heman10x-NGU

Copy link
Copy Markdown

What

The file backend now keeps the md5 ETag of each object in an xattr. GET, HEAD and range reads reuse it instead of hashing the whole file again. The ETag value does not change.

This affects deployments that use the file backend: self-hosted Supabase and the local CLI stack. Hosted Supabase uses the S3 backend.

Refs #612

Why

With the default md5 ETag algorithm, every read hashes the full object before the response starts. A HEAD, or a range read of the first 1 KB, of a 1 GB file reads all 1 GB first. #612 reported this. #613 added mtime as an opt-in and kept md5 as the default for compatibility. Caching keeps md5 ETags valid for existing clients and caches.

How

etag() now calls cachedMd5(). It reads a new xattr (user.supabase.md5 on Linux, com.apple.metadata.supabase.md5 on macOS) holding <inode>-<mtime>-<size>:<md5>. If all three match the file, the stored md5 is returned. If not, the file is hashed as before and the xattr is written.

  • Uploads already hash the staged file once in headFile(). The xattr is written there and moves with the file on rename.
  • copyObject writes with copyFile, which can keep the destination's inode. It removes the destination's cached md5 right after the copy.
  • The first read of an object with no valid cache, such as any object stored before this change, still costs a full hash plus one xattr write.
  • If the xattr cannot be written (for example a read-only volume), the md5 is still returned.
  • The mtime algorithm is unchanged.

Limits and side effects:

  • A same-size file rewritten in place outside Storage keeps its old md5 if its mtime does not change. That happens with touch -r, rsync --inplace -t, or a rewrite in the same mtime tick.
  • A file renamed over the path during a hash can get the old file's md5. That value holds the old inode, so it never matches and costs one extra hash.
  • The first read of an uncached object writes an xattr. This bumps ctime and sends inotify IN_ATTRIB, so ctime-based backups see each old object change once.
  • Each GET and HEAD reads one more small xattr. The backend already reads three.

Benchmark

The script below uploads one object through uploadObject() and does one warm-up read. It then times headObject(), getObject() until the body is returned, and a Range: bytes=0-1023 read with the body consumed. It also counts the bytes read through fs.createReadStream before each response. The same script ran on master and on this branch.

M4 MacBook Air, 16 GB, APFS, Node 22.21.0. 1 GB object, 7 runs, median (min to max):

Call master this branch
headObject 1557 ms (1333 to 2815) 0.17 ms (0.13 to 0.24)
getObject, time to body 1356 ms (1334 to 2683) 0.17 ms (0.14 to 0.44)
getObject, 1 KB range 1341 ms (1333 to 2814) 0.31 ms (0.23 to 0.84)
Bytes read before each response 1,073,741,824 0 (range: 1,024)

The ETag was the same md5 on both branches. Upload time is unchanged.

Caveats: the page cache was warm, so these numbers mostly measure md5 CPU time. Cold cache, slower disks and Linux were not measured.

Benchmark script

Run from a checkout so tsx picks up the repo's path aliases:
STORAGE_FILE_BACKEND_PATH=<tmp dir> npx tsx bench-file-etag.ts <repo dir> <size MB> <runs>

// Benchmark: FileBackend read latency with the default md5 ETag algorithm.
// Usage (cwd = a storage worktree, so tsx picks up its tsconfig paths):
//   STORAGE_FILE_BACKEND_PATH=<tmpdir> npx tsx <this file> <repoDir> <sizeMB> <runs>
// Measures, per run, on the same file:
//   head:  headObject() latency
//   get:   getObject() latency until the body stream is returned (time to first byte)
//   range: getObject() with "Range: bytes=0-1023", full body consumed
// The object is uploaded once through uploadObject() (the real write path),
// then one warm-up read is done so page cache is hot for both versions.
import fs from 'node:fs'
import * as fsp from 'node:fs/promises'
import path from 'node:path'
import { Readable } from 'node:stream'

const [repoDir, sizeArg = '1024', runsArg = '7'] = process.argv.slice(2)
const sizeMB = Number(sizeArg)
const runs = Number(runsArg)
const root = process.env.STORAGE_FILE_BACKEND_PATH!
process.env.STORAGE_FILE_ETAG_ALGORITHM = 'md5'

async function main() {
  const { FileBackend } = await import(path.join(repoDir, 'src/storage/backend/file.ts'))
  await fsp.mkdir(root, { recursive: true })
  const backend = new FileBackend()

  // Count bytes read by every fs.createReadStream (hashing + body).
  let bytesRead = 0
  const orig = fs.createReadStream
  ;(fs as any).createReadStream = (...args: any[]) => {
    const s = (orig as any)(...args)
    s.on('data', (c: Buffer) => (bytesRead += c.length))
    return s
  }

  const chunk = Buffer.alloc(1024 * 1024, 7)
  async function* gen() {
    for (let i = 0; i < sizeMB; i++) yield chunk
  }
  const tUp = performance.now()
  const up = await backend.uploadObject('b', 'big.bin', 'v1', Readable.from(gen()), 'application/octet-stream', 'no-cache')
  const uploadMs = performance.now() - tUp
  // warm-up read (page cache)
  await backend.headObject('b', 'big.bin', 'v1')

  const results: Record<string, number[]> = { head: [], get: [], range: [] }
  const reads: Record<string, number[]> = { head: [], get: [], range: [] }
  const etags = new Set<string>([up.eTag])

  for (let i = 0; i < runs; i++) {
    bytesRead = 0
    let t = performance.now()
    const h = await backend.headObject('b', 'big.bin', 'v1')
    results.head.push(performance.now() - t)
    reads.head.push(bytesRead)
    etags.add(h.eTag)

    bytesRead = 0
    t = performance.now()
    const g = await backend.getObject('b', 'big.bin', 'v1')
    results.get.push(performance.now() - t)
    // count only bytes read before the body is handed out
    reads.get.push(bytesRead)
    ;(g.body as fs.ReadStream).destroy()
    etags.add(g.metadata.eTag)

    bytesRead = 0
    t = performance.now()
    const r = await backend.getObject('b', 'big.bin', 'v1', { range: 'bytes=0-1023' })
    for await (const _ of r.body as Readable) {
    }
    results.range.push(performance.now() - t)
    reads.range.push(bytesRead)
    etags.add(r.metadata.eTag)
  }

  const stat = (xs: number[]) => {
    const s = [...xs].sort((a, b) => a - b)
    return { median: s[Math.floor(s.length / 2)], min: s[0], max: s[s.length - 1] }
  }
  const fmt = (n: number) => n.toFixed(2)
  console.log(`repo=${repoDir} size=${sizeMB}MB runs=${runs} node=${process.version}`)
  console.log(`upload ms=${fmt(uploadMs)} etags=${[...etags].join(',')}`)
  for (const k of Object.keys(results)) {
    const s = stat(results[k])
    console.log(
      `${k.padEnd(5)} median=${fmt(s.median)}ms min=${fmt(s.min)} max=${fmt(s.max)} bytesReadBeforeResponse(median)=${stat(reads[k]).median}`
    )
  }
  await fsp.rm(root, { recursive: true, force: true })
}

main().catch((e) => {
  console.error(e)
  process.exit(1)
})

Tests

New tests in file.test.ts use an xattr mock that keys values by inode.

  • Fail on master, pass here: reads after an upload do not hash the file again.
  • Pass here, and fail if the code only checked mtime and size or skipped the copy cleanup: a file renamed over the path mid-hash, and a copy over a same-size destination with the same mtime, both return the new md5.
  • A failed copy precondition writes no object metadata attribute.
  • npx vitest run --config vitest.unit.config.ts: 224 test files, 4493 tests pass. npx tsc --noEmit and npx biome check . (850 files) pass.

Not tested

  • Linux file systems (ext4, XFS, overlayfs in Docker). The code uses the same fs-xattr calls the backend already uses for content type and cache control.
  • A cold page cache.
  • The HTTP routes end to end. The integration suite needs Postgres and Docker, and the change is inside FileBackend only.
  • Node 26, which package.json asks for. Tests ran on Node 22.21.0.

The file backend hashed the whole object with md5 on every GET, HEAD and
range read before sending a byte. The checksum is now stored in an xattr
with the file's inode, mtime and size, and reused while all three match.
A copy over an existing destination drops its cached checksum.
@Heman10x-NGU
Heman10x-NGU requested a review from a team as a code owner November 27, 2026 15:42

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant