Build a Real-Time Bidding Engine with Supabase Realtime
View full size On this page
A real-time bidding engine built on Supabase Realtime uses PostgreSQL triggers to validate bids and update auction state. Postgres Changes and Broadcast push those updates to every connected client over WebSockets. This removes polling loops and separate WebSocket servers. It also keeps bid validation, race-condition locking, and notification logic inside the database itself.
Key takeaways
- Supabase Realtime subscribes to PostgreSQL's Write-Ahead Log. This means every bid insert and auction update reaches connected clients over WebSockets, with no separate pub/sub service needed.
- PostgreSQL triggers with
SELECT ... FOR UPDATErow locking, orpg_advisory_xact_lock(), stop two simultaneous bids from both reading the same high-bid value. - Postgres Changes handles saved state such as bids and auction status. Broadcast handles short-lived notifications like outbid alerts. Presence tracks who is watching an auction.
REPLICA IDENTITY FULLand asupabase_realtimepublication must both be set up before Realtime sends full row data on UPDATE and DELETE events.- Supabase's Pro tier supports hundreds of concurrent Realtime connections per project for $25 a month. That's enough for most mid-size auction platforms, with no self-hosted WebSocket server needed.
Updated 20 November 2026: sources added, experience claims checked against our project record, summary added.
Architecture Overview
Before writing any code, let's look at what we're building and how the pieces fit together.
Supabase Realtime gives you three tools that fit auction needs:
- Postgres Changes: Subscribe to INSERT, UPDATE, and DELETE events on your bid and auction tables. When someone places a bid, every subscriber gets the new row data within milliseconds.
- Broadcast: Send short-lived messages to channel members. Good for "you've been outbid" alerts that don't need to be saved.
- Presence: Track who's watching an auction right now. This lets you show "14 bidders watching" in your UI and spot ghost sessions.
The data flow looks like this:
- Bidder submits a bid through your frontend
- An RPC call or direct insert hits your
bidstable - A PostgreSQL trigger checks the bid amount and updates
auctions.current_high_bid - Supabase Realtime picks up the WAL change and pushes it to all subscribers on that auction's channel
- A second trigger fires a Broadcast event to tell the previous high bidder they've been outbid
- Every connected client updates its UI in real time
End-to-end delay from bid placement to UI update is usually fast enough to feel instant. Realtime pushes changes as soon as PostgreSQL commits them, well within normal network round-trip times.
Why Not Just Use Polling?
You might ask: why not just poll every 500ms? You can, but at 200 concurrent bidders on one auction, that's 400 requests per second hitting your database, for just one auction. Multiply that by 50 active auctions and you're at 20,000 queries per second. Most of those return nothing new. WebSockets flip this model: zero queries when nothing changes, instant updates when something does.
Database Schema and Setup
Here's a schema that works for most auction types. It's kept simple on purpose. You can extend it, but this core structure covers the common cases.
-- Auctions table
CREATE TABLE auctions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
item_name TEXT NOT NULL,
description TEXT,
starting_price DECIMAL(12,2) NOT NULL DEFAULT 0,
current_high_bid DECIMAL(12,2) DEFAULT 0,
highest_bidder_id UUID REFERENCES auth.users(id),
min_increment DECIMAL(12,2) DEFAULT 1.00,
status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('scheduled', 'active', 'ended', 'sold', 'cancelled')),
starts_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ends_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '30 minutes',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Bids table
CREATE TABLE bids (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
auction_id UUID NOT NULL REFERENCES auctions(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES auth.users(id),
amount DECIMAL(12,2) NOT NULL,
placed_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT positive_amount CHECK (amount > 0)
);
-- Index for fast bid lookups per auction
CREATE INDEX idx_bids_auction_amount ON bids(auction_id, amount DESC);
CREATE INDEX idx_bids_auction_time ON bids(auction_id, placed_at DESC);
-- Critical: enable replica identity for Realtime
ALTER TABLE auctions REPLICA IDENTITY FULL;
ALTER TABLE bids REPLICA IDENTITY FULL;
The REPLICA IDENTITY FULL setting matters a lot. Without it, Supabase Realtime only gets the primary key on UPDATE and DELETE events, not the full row data. For an auction system, you need the full payload so clients can update bid amounts without a separate query.
Enabling Realtime Replication
In the Supabase Dashboard, go to Database → Replication and turn on replication for both the auctions and bids tables. You can also do this with SQL:
BEGIN;
-- Remove existing publication if it exists
DROP PUBLICATION IF EXISTS supabase_realtime;
-- Create publication with both tables
CREATE PUBLICATION supabase_realtime FOR TABLE auctions, bids;
COMMIT;
Row-Level Security
Don't skip this. RLS is your server-side check layer.
ALTER TABLE auctions ENABLE ROW LEVEL SECURITY;
ALTER TABLE bids ENABLE ROW LEVEL SECURITY;
-- Anyone can view active auctions
CREATE POLICY "Public auction viewing" ON auctions
FOR SELECT USING (status IN ('active', 'ended', 'sold'));
-- Authenticated users can view all bids on active auctions
CREATE POLICY "View bids on active auctions" ON bids
FOR SELECT USING (
EXISTS (
SELECT 1 FROM auctions
WHERE auctions.id = bids.auction_id
AND auctions.status = 'active'
)
);
-- Only authenticated users can place bids
CREATE POLICY "Place bids" ON bids
FOR INSERT WITH CHECK (
auth.uid() = user_id
AND EXISTS (
SELECT 1 FROM auctions
WHERE auctions.id = auction_id
AND auctions.status = 'active'
AND auctions.ends_at > NOW()
)
);
PostgreSQL Triggers for Bid Logic
This is where the real logic lives. The database checks all bids on the server side, so the client can't cheat.
Bid Validation and Auction Update Trigger
CREATE OR REPLACE FUNCTION process_new_bid()
RETURNS TRIGGER AS $$
DECLARE
v_auction auctions%ROWTYPE;
BEGIN
-- Lock the auction row to prevent race conditions
SELECT * INTO v_auction
FROM auctions
WHERE id = NEW.auction_id
FOR UPDATE;
-- Validate auction is active
IF v_auction.status != 'active' THEN
RAISE EXCEPTION 'Auction is not active';
END IF;
-- Validate auction hasn't ended
IF v_auction.ends_at < NOW() THEN
RAISE EXCEPTION 'Auction has ended';
END IF;
-- Validate bid amount exceeds current high + minimum increment
IF NEW.amount < v_auction.current_high_bid + v_auction.min_increment THEN
RAISE EXCEPTION 'Bid must be at least % higher than current high bid of %',
v_auction.min_increment, v_auction.current_high_bid;
END IF;
-- Prevent self-outbidding
IF v_auction.highest_bidder_id = NEW.user_id THEN
RAISE EXCEPTION 'You are already the highest bidder';
END IF;
-- Update auction with new high bid
UPDATE auctions
SET
current_high_bid = NEW.amount,
highest_bidder_id = NEW.user_id,
updated_at = NOW()
WHERE id = NEW.auction_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER validate_and_process_bid
BEFORE INSERT ON bids
FOR EACH ROW
EXECUTE FUNCTION process_new_bid();
That FOR UPDATE lock on the auction row is key. Without it, two bids arriving at the same time could both read the same current_high_bid, both pass the check, and both get inserted. The lock forces them to happen one at a time.
Broadcast Outbid Notifications
This trigger fires after a bid succeeds and sends a short-lived notice to the auction channel:
CREATE OR REPLACE FUNCTION notify_outbid()
RETURNS TRIGGER AS $$
DECLARE
v_previous_bidder UUID;
BEGIN
-- Find who just got outbid
SELECT user_id INTO v_previous_bidder
FROM bids
WHERE auction_id = NEW.auction_id
AND id != NEW.id
ORDER BY amount DESC
LIMIT 1;
-- Broadcast outbid notification if there was a previous bidder
IF v_previous_bidder IS NOT NULL THEN
PERFORM realtime.send(
jsonb_build_object(
'auction_id', NEW.auction_id,
'new_high', NEW.amount,
'outbid_user', v_previous_bidder,
'new_leader', NEW.user_id
),
'outbid',
'auction:' || NEW.auction_id::text,
true
);
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER after_bid_notify
AFTER INSERT ON bids
FOR EACH ROW
EXECUTE FUNCTION notify_outbid();
Client-Side Subscription with JavaScript
Now let's wire up the frontend with plain JavaScript and React patterns. The same approach works with Next.js or any other framework.
Initialize the Client
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
{
realtime: {
params: {
eventsPerSecond: 20 // Throttle for auction traffic
}
}
}
);
That eventsPerSecond setting matters. On a hot auction with dozens of bids per second, you don't want to re-render 50 times a second. Twenty updates per second is plenty for a smooth UI.
Subscribe to an Auction Channel
function subscribeToAuction(auctionId, callbacks) {
const channel = supabase.channel(`auction:${auctionId}`);
channel
// Listen for new bids via Postgres Changes
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'bids',
filter: `auction_id=eq.${auctionId}`
}, (payload) => {
callbacks.onNewBid(payload.new);
})
// Listen for auction status changes
.on('postgres_changes', {
event: 'UPDATE',
schema: 'public',
table: 'auctions',
filter: `id=eq.${auctionId}`
}, (payload) => {
callbacks.onAuctionUpdate(payload.new);
})
// Listen for outbid broadcast notifications
.on('broadcast', { event: 'outbid' }, ({ payload }) => {
callbacks.onOutbid(payload);
})
// Track active bidders via Presence
.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState();
const bidderCount = Object.keys(state).length;
callbacks.onPresenceUpdate(bidderCount, state);
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
// Track this user's presence
await channel.track({
user_id: supabase.auth.getUser()?.data?.user?.id,
status: 'watching',
joined_at: new Date().toISOString()
});
}
});
return channel;
}
React Hook for Auction Subscriptions
import { useState, useEffect, useCallback } from 'react';
function useAuction(auctionId) {
const [auction, setAuction] = useState(null);
const [bids, setBids] = useState([]);
const [bidderCount, setBidderCount] = useState(0);
const [isOutbid, setIsOutbid] = useState(false);
useEffect(() => {
// Fetch initial state
async function loadAuction() {
const { data: auctionData } = await supabase
.from('auctions')
.select('*')
.eq('id', auctionId)
.single();
setAuction(auctionData);
const { data: bidData } = await supabase
.from('bids')
.select('*')
.eq('auction_id', auctionId)
.order('amount', { ascending: false })
.limit(20);
setBids(bidData || []);
}
loadAuction();
// Subscribe to real-time updates
const channel = subscribeToAuction(auctionId, {
onNewBid: (bid) => {
setBids(prev => [bid, ...prev].slice(0, 20));
setIsOutbid(false);
},
onAuctionUpdate: (updated) => setAuction(updated),
onOutbid: (payload) => {
const currentUser = supabase.auth.getUser()?.data?.user;
if (payload.outbid_user === currentUser?.id) {
setIsOutbid(true);
}
},
onPresenceUpdate: (count) => setBidderCount(count)
});
return () => {
supabase.removeChannel(channel);
};
}, [auctionId]);
const placeBid = useCallback(async (amount) => {
const user = (await supabase.auth.getUser()).data.user;
const { data, error } = await supabase
.from('bids')
.insert({
auction_id: auctionId,
amount: parseFloat(amount),
user_id: user.id
})
.select()
.single();
if (error) throw new Error(error.message);
return data;
}, [auctionId]);
return { auction, bids, bidderCount, isOutbid, placeBid };
}
Handling Race Conditions and Bid Validation
Race conditions cause more bugs in auction systems than anything else. Here's how to handle them.
Server-Side: PostgreSQL Does the Heavy Lifting
The SELECT ... FOR UPDATE in the trigger function above is your first line of defense. Advisory locks are another good pattern for high-traffic auctions:
CREATE OR REPLACE FUNCTION place_bid_safe(
p_auction_id UUID,
p_user_id UUID,
p_amount DECIMAL
)
RETURNS TABLE(bid_id UUID, new_high DECIMAL) AS $$
DECLARE
v_lock_key BIGINT;
v_bid_id UUID;
BEGIN
-- Generate a deterministic lock key from auction UUID
v_lock_key := ('x' || left(p_auction_id::text, 15))::bit(64)::bigint;
-- Acquire advisory lock (blocks concurrent bids on same auction)
PERFORM pg_advisory_xact_lock(v_lock_key);
-- Now safe to insert (trigger handles validation)
INSERT INTO bids (auction_id, user_id, amount)
VALUES (p_auction_id, p_user_id, p_amount)
RETURNING id INTO v_bid_id;
RETURN QUERY
SELECT v_bid_id, p_amount;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
Call this from the client with Supabase's RPC:
const { data, error } = await supabase.rpc('place_bid_safe', {
p_auction_id: auctionId,
p_user_id: user.id,
p_amount: bidAmount
});
Client-Side: Optimistic UI with Rollback
Show the bid right away in the UI, but be ready to roll it back if the server rejects it:
async function handleBidSubmit(amount) {
const optimisticBid = {
id: crypto.randomUUID(),
amount,
user_id: user.id,
placed_at: new Date().toISOString(),
_optimistic: true
};
// Show immediately
setBids(prev => [optimisticBid, ...prev]);
try {
await placeBid(amount);
// Real bid will arrive via Realtime and replace optimistic one
} catch (err) {
// Remove optimistic bid on failure
setBids(prev => prev.filter(b => b.id !== optimisticBid.id));
showError(err.message);
}
}
Presence Tracking for Active Bidders
Showing how many people are watching an auction builds urgency. Presence tracking is simple with Supabase:
// Update user status when they start bidding
async function updatePresenceStatus(channel, status) {
await channel.track({
user_id: user.id,
status, // 'watching', 'bidding', 'won'
last_active: new Date().toISOString()
});
}
On the display side, you can break down the presence state to show how many people are actively bidding versus just watching:
function parseBidderStats(presenceState) {
const users = Object.values(presenceState).flat();
return {
total: users.length,
bidding: users.filter(u => u.status === 'bidding').length,
watching: users.filter(u => u.status === 'watching').length
};
}
Performance Tuning and Production Considerations
Throttling and Debouncing
A bidding war can create dozens of events per second. Here's what to set up:
- Server-side:
eventsPerSecond: 20on the Supabase client config - Client-side: Debounce the bid button at 300ms to stop double-clicks
- UI updates: Use
requestAnimationFramefor bid list animations
Auction End Timing
Don't trust the client clock. Use a PostgreSQL cron job with pg_cron:
-- Run every 10 seconds to close expired auctions
SELECT cron.schedule(
'close-expired-auctions',
'*/10 * * * * *',
$$
UPDATE auctions
SET status = CASE
WHEN highest_bidder_id IS NOT NULL THEN 'sold'
ELSE 'ended'
END
WHERE status = 'active'
AND ends_at <= NOW();
$$
);
Anti-Snipe Extension
Most auction platforms push back the deadline if a bid lands in the last few seconds:
-- Add to the process_new_bid trigger
IF v_auction.ends_at - NOW() < INTERVAL '30 seconds' THEN
UPDATE auctions
SET ends_at = ends_at + INTERVAL '30 seconds'
WHERE id = NEW.auction_id;
END IF;
Supabase Realtime vs Alternatives
Here's a comparison based on each platform's public docs and limits:
| Feature | Supabase Realtime | Pusher | Ably | Firebase RTDB | Socket.io (self-hosted) |
|---|---|---|---|---|---|
| Native DB sync | PostgreSQL WAL (built-in) | Separate service required | Separate service required | JSON tree sync | Manual, you wire it up |
| Latency | Low, typically sub-second | Low | Low | Low | Depends on your infrastructure |
| Max events/sec | 200k+ | Vendor-dependent | Vendor-dependent | Vendor-dependent | Unlimited, you scale it |
| Auth integration | Built-in (RLS + JWT) | Custom | Token-based | Firebase Auth | Custom |
| Presence | Built-in | Built-in | Built-in | Built-in | Build it yourself |
| Free tier | 500K MAU, 200 concurrent | Limited free plan | Limited free plan | Limited free plan | Free (hosting costs apply) |
| Pro pricing | $25/mo | Paid tiers available | Paid tiers available | Pay-as-you-go | Hosting costs vary (e.g. AWS) |
| Best for | DB-centric real-time apps | Simple pub/sub | High reliability | Mobile apps | Full control |
For an auction system, Supabase wins because your bids already live in PostgreSQL. You don't need to sync between a database and a separate pub/sub system. The bid hits the DB, and the DB triggers the WebSocket push. One source of truth.
If you're building on a headless CMS architecture, Supabase fits naturally alongside content delivery without adding another service to manage.
Deploying and Scaling Your Auction System
For most projects, Supabase's managed Pro tier at $25 a month handles a high volume of daily auctions with ease. Here's what to watch:
- Connection limits: The Pro tier gives you 500 concurrent Realtime connections. If you need more, upgrade or add connection pooling on the client.
- WAL size: High-volume bidding creates a lot of WAL traffic. Watch your replication slot to avoid disk bloat.
- Channel count: Each auction gets its own channel. With thousands of active auctions, check that your client properly unsubscribes from ended ones.
For a frontend built with Astro or Next.js, the Supabase JS client works the same way. Just make sure you start it client-side for Realtime subscriptions.
If you're building something that needs to handle serious scale, hundreds of thousands of concurrent bidders, reach out to us. Our work on Not Another Sunday, a directory built on Next.js and Supabase with 137K listings, gives us a feel for how connection limits and WAL throughput behave at that kind of scale, so we can help you plan ahead. You can also check our pricing page for project-based work.
FAQ
How many concurrent bidders can Supabase Realtime handle?
Supabase Realtime can process a high volume of events per second on its managed platform, and the Pro tier supports hundreds of concurrent connections per project for $25 a month. Enterprise plans raise those limits, and the Realtime server is open source, so you can self-host it for bigger deployments.
Is Supabase Realtime fast enough for a live auction?
Yes. End-to-end delay from bid insertion to client notice is usually well under a second in production, fast enough that updates feel instant to users, since human reaction time is far slower than that delay, especially next to a normal webpage click response. The usual bottleneck is a user's own network connection, not Supabase's infrastructure.
How do I prevent race conditions when two people bid simultaneously?
Use PostgreSQL's SELECT ... FOR UPDATE row-level locking inside a trigger function, or an advisory lock with pg_advisory_xact_lock(), to process bids one at a time per auction. The losing bid still gets checked against the updated high bid, and either wins if it's still higher or fails with a clear error message.
Can I use Supabase Realtime with Next.js or Astro?
Yes. The @supabase/supabase-js client works in any JavaScript setup, so the same subscription code runs in Next.js client components (started inside a useEffect hook) and in Astro client-side islands, since Realtime connections need the browser's WebSocket API rather than server-side rendering.
What happens if a user's connection drops mid-auction?
Supabase Realtime tries to reconnect on its own when a client drops, and once it resubscribes it gets the current channel state again. For critical auctions, it's worth also fetching the latest auction data with a standard query after reconnecting, since some updates can be missed during the gap. The Presence system removes a disconnected user after a timeout.
How do I handle auction end times accurately?
Never rely on client-side timers to decide when an auction ends, since they can be faked or drift out of sync. Use PostgreSQL's pg_cron extension instead to check for and close expired auctions every 10 seconds on the server, then send clients the server timestamp for countdown display only.
Is Supabase Realtime free for small projects?
Yes. Supabase's free tier includes Realtime with up to 200 concurrent connections and 500,000 monthly active users, enough for a hobby project or an early MVP. Production auction platforms with real traffic should plan to move to the Pro tier at $25 a month, still far cheaper than running your own WebSocket server.
How do I test a real-time bidding system locally?
Use the Supabase CLI's supabase start command to run a local Supabase instance with Realtime enabled, then open multiple browser tabs to mimic separate bidders. For load testing, write a Node.js script that spins up 100 or more Supabase clients bidding against each other on a timer. This helps surface race conditions and tune the eventsPerSecond setting before launch.