Le Duy Khuong

Chuỗi: supabase-series · Phần 9

Năng suất & công cụ dev

Realtime và Edge Functions

Realtime subscriptions; Edge Functions (webhook). Khi nào dùng; ranh giới serverless, event-driven.

2026-03-173 phút đọcVI

Realtime and Edge Functions

Introduction

Supabase provides Realtime (subscribe to table changes over WebSocket) and Edge Functions (serverless Deno at the edge, with access to Auth and DB). This post summarizes Realtime subscriptions, Edge Functions (e.g. webhook), and when to use them — aligned with serverless and event-driven boundaries.

Goal: Enable Realtime and subscribe simply; create and invoke an Edge Function; choose the right use case (realtime vs poll, edge vs backend).

Features

Realtime

  • Mechanism: Supabase uses Postgres replication slot; changes (INSERT/UPDATE/DELETE) on tables are broadcast over WebSocket. Client subscribes by channel (e.g. table + filter).
  • Use when: UI must update as soon as data changes (chat, dashboard, notifications) without polling.
  • RLS: Realtime still respects RLS; client only receives events for rows the policy allows reading.

Edge Functions

  • Mechanism: Serverless functions (Deno) deployed to Supabase; invoked via HTTP or from client. Can read env, call Supabase client (Auth, DB), call external APIs.
  • Use when: Webhooks from third parties, post-auth processing (e.g. sync profile), light jobs that don't need a long-running server.
  • Limits: Runtime and memory are limited; heavy logic or queues should go to a separate backend/worker.

Workflow / Process

  1. Realtime: Bật Realtime cho bảng (Dashboard → Database → Replication) hoặc publication; client supabase.channel('...').on('postgres_changes', { event: '*', schema: 'public', table: 'messages' }, callback).subscribe().
  2. Edge Function: Viết hàm trong supabase/functions/<tên>/index.ts; deploy supabase functions deploy <tên>. Gọi từ client hoặc từ webhook (invoke URL + key).
  3. Quyết định dùng gì: Realtime khi cần push ngay từ DB; Edge khi cần chạy code ở edge (webhook, transform). Poll đơn giản vẫn hợp lý nếu tần suất thấp và không cần latency thấp.

Quy ước: Bật Realtime chỉ cho bảng cần; Edge Function không lưu secret trong code (dùng env), không làm logic quá nặng.

Sample code

Subscribe Realtime (client)

const channel = supabase
  .channel('messages')
  .on(
    'postgres_changes',
    { event: 'INSERT', schema: 'public', table: 'messages', filter: `conversation_id=eq.${convId}` },
    (payload) => {
      console.log('New message', payload.new);
    }
  )
  .subscribe();
// Cleanup: channel.unsubscribe();

Edge Function (Deno) — webhook echo

// supabase/functions/webhook-echo/index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
 
serve(async (req) => {
  const body = await req.json();
  // Validate, then e.g. insert to DB or call external API
  return new Response(JSON.stringify({ received: true }), {
    headers: { 'Content-Type': 'application/json' },
    status: 200,
  });
});

Deploy: supabase functions deploy webhook-echo. Gọi: POST tới URL function + header Authorization: Bearer <anon key> (hoặc key riêng nếu cấu hình).

Áp dụng trong kiến trúc

  • Ranh giới serverless: Edge Functions là ranh giới “code chạy theo request, không state”; logic dài hoặc stateful nên đưa vào backend/queue. Realtime là kênh event từ DB, không thay thế message queue cho throughput lớn.
  • Event-driven: Realtime dùng khi “sự kiện = thay đổi row”; Edge dùng khi “sự kiện = HTTP request (webhook)”. Thiết kế rõ nguồn sự kiện và consumer tránh duplicate hoặc loop.
  • Bảo mật: Edge Function nhận request từ internet; validate input, dùng env cho secret, không log token. Realtime đã gắn RLS nên client chỉ nhận event đúng quyền.

Kết

Realtime phù hợp cập nhật UI theo thay đổi bảng; Edge Functions phù hợp webhook và xử lý nhẹ ở edge. Bài cuối sẽ nói deploy, CI/CD và multi-project.

Bài tiếp: 10 — Deploy, CI/CD và multi-project

Đọc thêm: Supabase Realtime, Edge Functions

LDK

Le Duy Khuong

AI Transformation & Digital Strategy. Writing about agentic systems, engineering leadership, and building in public.