惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
小众软件
小众软件
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
Jina AI
Jina AI
博客园 - 【当耐特】
V
Visual Studio Blog
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
量子位
IT之家
IT之家
G
Google Developers Blog
V
V2EX
The GitHub Blog
The GitHub Blog
月光博客
月光博客
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Two days lost to PGRST116: when Supabase RLS hides a succ...
Vadym Arnaut · 2026-05-14 · via DEV Community

TL;DR. Our Supabase upsert wrote the row. The chained .select().single() returned PGRST116. The wrapper read that as a failed write. The frontend retried. The retry was wrong. Two days to find why.

We've been running an LMS on Supabase for the past several months — auth, RLS on every table, FastAPI talking to Postgres. The bug below cost us two days last quarter, and the fix changed how we read PGRST116 in our wrapper.

The setting

We have a quiz_attempts table. Each attempt gets created on quiz start, updated as the student progresses. The update is an upsert because a retry of the same attempt_id should patch the existing row, not insert a duplicate.

const { data, error } = await supabase
  .from('quiz_attempts')
  .upsert({ id, student_id, quiz_id, attempt_count })
  .select()
  .single();

Enter fullscreen mode Exit fullscreen mode

The .select().single() chain returns the upserted row so we can show the student their new state.

RLS policies, simplified:

create policy "students write their own attempts"
on quiz_attempts for all to authenticated
using (student_id = auth.uid())
with check (student_id = auth.uid());

create policy "students read their own attempts"
on quiz_attempts for select to authenticated
using (student_id = auth.uid() and is_visible = true);

Enter fullscreen mode Exit fullscreen mode

The SELECT policy carries an extra is_visible check that the write policy doesn't. That asymmetry is the seam the bug walks through.

The bug

A trigger on quiz_attempts flips is_visible to false under a corner case (timing relative to a parallel write from an admin tool — the specifics aren't the point). The student's upsert committed: their fields were written, the row is theirs.

Then .select().single() runs. The SELECT policy applies. is_visible = false. PostgREST returns:

{
  "code": "PGRST116",
  "details": "Results contain 0 rows",
  "message": "JSON object requested, multiple (or no) rows returned"
}

Enter fullscreen mode Exit fullscreen mode

Our runtime wrapper auto-threw on any .error. To the upstream code, this looked identical to a failed upsert. The frontend retried with the same payload. The retry hit the same trigger. The user state diverged from the DB state. Etc.

Why this was hard

PGRST116 has two completely different meanings when it comes after a mutation:

  1. The upsert truly failed — constraint violation, missing required field, RLS denied the write.
  2. The upsert succeeded — RLS just hid the returned row from the caller.

The wrapper conflated them. The PostgrestError code is identical. The HTTP status is identical (406). The only difference lives in the database, which the client can't see.

Two days of logs because we kept treating "no row returned" as "no row written."

The fix

Three changes.

1. Don't auto-throw on PGRST116 from a .select().single() chained off a mutation. Treat it as ambiguous and route to a separate branch:

async function safeUpsertReturning(query) {
  const { data, error } = await query;
  if (!error) return { data, error: null };
  if (error.code === 'PGRST116') {
    // The mutation may have succeeded; we just can't read the row.
    return { data: null, error: null, hidden: true };
  }
  throw error;
}

Enter fullscreen mode Exit fullscreen mode

2. Service-role verification. When the wrapper returns hidden: true, the backend does a service-role read by id to confirm whether the row actually exists. Yes → success-without-readback (treat as written). No → real failure, propagate. The client never branches on this directly.

3. Observability tying client errors to DB state. Every PGRST116 from the wrapper emits a structured event with the query shape and request id. Server-side, we log the same id with the actual row state visible to service role. Correlating the two would have surfaced the mismatch on day one.

What I'd tell past-us

PGRST116 is not a write error. It's a visibility error.

Your wrapper, your error handler, your retry logic — each should know which one it's seeing. If your stack can't tell the difference, you're going to retry successful writes. The kind of bug that produces is the kind where the symptom and the cause are twelve layers apart.

What I want to hear back

  • Do you separate "write failed" from "write succeeded but I can't read it" in your Supabase code? What does the wrapper look like?
  • Has anyone built a Postgres-side audit trigger that captures "row was written but RLS hid it from the writer"? Curious about the shape.
  • For service-role verification — anything safer than select(*).eq('id', id) you've used?

The project that runs this stack is open source:

GitHub logo ArVaViT / equip

Free, open-source LMS for Bible schools, ministries, and nonprofit educational programs. React + FastAPI + Supabase.

Equip logo

Equip

A free, open-source learning management system built for Bible schools church ministries, and nonprofit educational programs

MIT License Backend CI Frontend CI Good first issues

Live demo · Roadmap · Contributing · Changelog


Why this project?

Hundreds of small Bible schools, home churches, and missionary training programs around the world still manage courses on paper, WhatsApp, or spreadsheets. Commercial LMS platforms are expensive, overkill, or require technical expertise that volunteer-run organizations simply don't have.

Equip is designed to change that:

  • Free forever — MIT-licensed, no paywalls, no "premium" tiers.
  • Simple to deploy — one-click Vercel deploy with a free Supabase database. No Docker, no servers to manage.
  • Built for small scale — optimized for 20-100 students, not enterprise pricing models.
  • Contributor-friendly — clear docs, conventional commits, issue templates, and a welcoming community.

Features

Area What you get
Course authoring Courses, modules, chapters, rich content blocks (TipTap editor with images, YouTube, callouts, audio)
Assessments Multiple-choice, true/false, short-answer, and essay