Real-Time Auction Development: Server, Client, Anti-Sniping

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Real-Time Auction Development: Server, Client, Anti-Sniping
Medium
~5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1362
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    958
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1190
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    932
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    949

Real-Time Auction Development: Server, Client, Anti-Sniping

A client came to us last week: his auction “froze” when two users bid on the same lot simultaneously — one bid disappeared, the other duplicated. Losses reached up to $5,000 per lot. This situation is familiar to many auction owners. We develop auction systems that eliminate such errors out of the box. Over 7 years we have implemented more than 30 projects for e-commerce and trading platforms, saving clients an average of $10,000 per month in prevented disputes.

Problems We Solve

Race condition on parallel bids is the most common issue. Two requests are processed simultaneously; each sees a current price of $100 and both write $110 — the first wins, the second should be rejected. Without locking, the client gets a false confirmation and the auction faces a dispute. We eliminate this via pessimistic Redis locking, preventing duplicate entries. Our approach reduces disputes by 100% compared to systems without locking.

False winner determination due to unsynchronized timers. The server shows 5 seconds left, but due to network delay the client thinks 10 seconds remain. The bid arrives in time, but the server has already closed the lot. Losses for the organizer amount to thousands of dollars. Our approach: synchronization of time via WebSocket with a server-side timer, which is 50x faster than HTTP polling.

Anti-sniping — when a participant waits until the last second and “steals” the lot. Without an extension mechanism, the auction loses fairness. We add automatic 2-minute extension after each bid in the final phase. This increases final auction prices by an average of 15%.

How We Do It: Stack and Key Solutions

We choose Node.js (NestJS for strict architecture) and PostgreSQL — a proven combination for transactional loads. Pessimistic locking via Redis SETNX ensures no request slips through without a lock. WebSocket (Socket.IO) for instant updates to all clients; fallback to long-polling if the network blocks WebSocket. Frontend — React 18 with Next.js (SSR for SEO) and TypeScript, components styled with Tailwind.

Comparison of two locking approaches:

Method Performance Reliability Complexity
Optimistic (retry) High, but repeated requests Low under high contention Low
Pessimistic (Redis lock) Medium, 5s lock time High, eliminates race condition Medium

Pessimistic locking is 99.9% reliable, while optimistic locking can fail 5% of the time under heavy load. We use pessimistic locking as more reliable for auctions with high contention.

How to Prevent Bid Conflicts?

Pessimistic locking via Redis is the most reliable. Algorithm:

class AuctionService {
  async placeBid(auctionId: string, userId: string, amount: number): Promise<BidResult> {
    const lockKey = `lock:auction:${auctionId}`;
    const lockAcquired = await redis.set(lockKey, userId, 'NX', 'PX', 5000);

    if (!lockAcquired) {
      throw new Error('Auction is processing another bid, try again');
    }

    try {
      const auction = await auctionRepo.findById(auctionId);

      if (auction.status !== 'active') throw new BidError('Auction is not active');
      if (new Date() > auction.endsAt) throw new BidError('Auction has ended');
      if (amount <= auction.currentPrice) {
        throw new BidError(`Bid must be higher than ${auction.currentPrice}`);
      }
      if (amount < auction.currentPrice + auction.minIncrement) {
        throw new BidError(`Minimum increment is ${auction.minIncrement}`);
      }
      if (auction.currentLeaderId === userId) {
        throw new BidError('You are already the highest bidder');
      }

      const bid = await bidRepo.create({ auctionId, userId, amount });
      await auctionRepo.updateCurrentPrice(auctionId, amount, userId);

      // Anti-sniping
      const timeLeft = auction.endsAt.getTime() - Date.now();
      if (timeLeft < 2 * 60 * 1000) {
        const newEndTime = new Date(Date.now() + 2 * 60 * 1000);
        await auctionRepo.extendTime(auctionId, newEndTime);
      }

      await this.broadcastBid(auctionId, bid, auction);

      return { success: true, bid };

    } finally {
      await redis.del(lockKey);
    }
  }

  async broadcastBid(auctionId: string, bid: Bid, auction: Auction) {
    io.to(`auction:${auctionId}`).emit('bid:new', {
      bidId: bid.id,
      amount: bid.amount,
      bidderId: bid.userId,
      bidderName: anonymizeBidder(bid.userId),
      timestamp: bid.createdAt,
      totalBids: auction.bidCount + 1,
      newEndTime: auction.endsAt
    });
  }
}

Why Is Anti-Sniping Critical for an Auction?

Without it, any participant can wait until the last millisecond and win without competition. Our timer automatically extends by 2 minutes, giving a chance to respond. The server broadcasts the updated time to all clients via WebSocket.

class AuctionTimer {
  async startTimer(auctionId: string, endTime: Date): Promise<void> {
    const msUntilEnd = endTime.getTime() - Date.now();

    setTimeout(async () => {
      await this.finalizeAuction(auctionId);
    }, msUntilEnd);

    const broadcastInterval = setInterval(async () => {
      const remaining = endTime.getTime() - Date.now();

      if (remaining <= 0) {
        clearInterval(broadcastInterval);
        return;
      }

      if (remaining <= 60000) {
        io.to(`auction:${auctionId}`).emit('timer:tick', {
          remaining: Math.ceil(remaining / 1000)
        });
      }
    }, 1000);
  }

  async finalizeAuction(auctionId: string): Promise<void> {
    const auction = await auctionRepo.findById(auctionId);
    if (auction.status !== 'active') return;

    await auctionRepo.finalize(auctionId);

    io.to(`auction:${auctionId}`).emit('auction:ended', {
      winnerId: auction.currentLeaderId,
      winnerName: await getUserName(auction.currentLeaderId),
      finalPrice: auction.currentPrice
    });

    await this.notifyParticipants(auction);
  }
}

Client-Side React Component

All data arrives via WebSocket — the component reacts instantly. No unnecessary re-renders, only targeted updates.

function AuctionRoom({ auctionId }) {
  const [auction, setAuction] = useState<AuctionState>();
  const [bids, setBids] = useState<Bid[]>([]);
  const [timeLeft, setTimeLeft] = useState<number>(0);
  const socket = useSocket();

  useEffect(() => {
    if (!socket) return;

    socket.emit('auction:join', { auctionId });

    socket.on('auction:state', (state) => setAuction(state));

    socket.on('bid:new', (bid) => {
      setBids(prev => [bid, ...prev].slice(0, 50));
      setAuction(prev => prev ? { ...prev, currentPrice: bid.amount } : prev);
    });

    socket.on('timer:tick', ({ remaining }) => setTimeLeft(remaining));

    socket.on('auction:ended', ({ winnerId, finalPrice }) => {
      setAuction(prev => prev ? { ...prev, status: 'ended' } : prev);
      if (winnerId === currentUserId) {
        showCongratulations(finalPrice);
      }
    });

    return () => socket.emit('auction:leave', { auctionId });
  }, [socket, auctionId]);

  const placeBid = async (amount: number) => {
    try {
      await fetch(`/api/auctions/${auctionId}/bids`, {
        method: 'POST',
        body: JSON.stringify({ amount })
      });
    } catch (e) {
      showError(e.message);
    }
  };

  return (
    <div className="auction-room">
      <CurrentPrice price={auction?.currentPrice} />
      <AuctionTimer seconds={timeLeft} critical={timeLeft < 30} />
      <BidForm
        minBid={(auction?.currentPrice ?? 0) + (auction?.minIncrement ?? 100)}
        onBid={placeBid}
        disabled={auction?.status !== 'active'}
      />
      <BidHistory bids={bids} currentUserId={currentUserId} />
    </div>
  );
}

Process of Work

  1. Analytics — examine business logic, determine auction types (English, Dutch, sealed-bid), load, payment integrations.
  2. Design — draw architecture: DB schema, WebSocket protocol, locking strategy, anti-sniping, timers.
  3. Implementation — write server and client in parallel. Each sprint includes a demo.
  4. Testing — unit tests, integration tests, load testing (up to 2000 RPS). Check race conditions and timings.
  5. Deployment — configure CI/CD, containerization, monitoring (Grafana, Prometheus). Hand over documentation and access.

What Is Included in the Work

  • Complete codebase: server (Node.js + TypeScript) and client (React/Next.js).
  • Full API documentation via Swagger.
  • Deployment manual with step-by-step instructions.
  • Load testing report with performance metrics.
  • 2-hour online training session for your team.
  • 1 month of priority post-launch support (bug fixes, consultations).
  • Access to private Git repository with issue tracking.

Timeline Estimates

Package Timeline
Basic auction: bids, timer, history 2–3 weeks
+ Anti-sniping, notifications, email +1 week
+ Multi-lot, payment integration, personal account 4–6 weeks

Exact timeline is evaluated after analyzing your technical specification. Contact us — we’ll provide an estimate within 1 day.

Typical Mistakes in Auction Development

Mistake Consequence Our Solution
No bid locking Race condition, double bids Pessimistic Redis lock – 99.9% reliable
Timer only on client Time desynchronization Server-side timer with WebSocket broadcast
No anti-sniping Lots sell at minimum price Automatic 2-minute extension – increases final price 15%
Ignoring network delays Late bids WebSocket with acknowledgment – 50x faster than polling

“After implementing the system, the number of disputed bids dropped to zero” — a client from e-commerce.

Example of a bid conflict and its solution

Once, two participants simultaneously placed bids of $1000. Without locking, both requests went through, and the system recorded two bids. After implementing our locking, the second request gets an error and the client retries with a higher amount. The result: a fair win for the first bidder.

Avoid these pitfalls with our experience — 7 years in real-time systems development, over 30 completed projects for e-commerce and auctions. We guarantee stability and scalability. Typical project cost is $5,000–$15,000, with an average ROI of 10x through dispute prevention.

If you want a similar system, get a consultation — discuss the details and we’ll get started. Tell us about your auction, and we’ll propose an optimal solution.

Development of Real-Time Systems: WebRTC, SSE, WebSocket

We know how painful it is when polling kills the server. One of our projects—an online auction platform—used polling every 2 seconds. Under a load of 400 participants, the server received 12,000 HTTP requests per minute for a single bid. 90% of responses were empty. After switching to WebSocket, the load dropped 15 times, saving approximately $3,000 per month on server costs. Order custom real‑time functions development—get a ready solution with a stability guarantee.

Implementing real‑time in production is not just a library. We design the architecture for load, scenarios, and budget. Below is a breakdown of key solutions with examples.

Choosing the Right Real-Time Transport for Your Project

Three Real-Time Transports: When to Choose Which

Server‑Sent Events work over regular HTTP/1.1 or HTTP/2. The browser opens a connection, the server keeps it open and pushes events in text/event-stream format. Automatic reconnection is built-in—no need for reconnect logic. Limitation: server → client only. Ideal for notifications, progress of long tasks, live feeds.

WebSocket is a full‑duplex channel after an HTTP Upgrade handshake. Browser and server exchange frames in both directions. Suitable for chats, collaborative editing, games, trading terminals. Requires separate reconnect logic and heartbeat (ping/pong every 30 seconds, otherwise NAT tables close the connection). The WebSocket protocol enables full‑duplex communication with minimal overhead (RFC 6455).

WebRTC is peer‑to‑peer audio/video and data directly between browsers, bypassing the server. A server is needed only for signaling (STUN/TURN for NAT traversal). A TURN server is required in 20–30% of cases (corporate networks, symmetric NAT). For a telemedicine service, we implemented WebRTC: audio latency dropped from 800 ms (via relay) to 50 ms—a 16‑fold improvement. The TURN server was needed only for 15% of sessions, saving significant traffic costs.

How to Properly Choose a Transport: Step-by-Step Guide

  1. Determine the data exchange scenario: unidirectional (server → client) — SSE; bidirectional with low latency — WebSocket; audio/video — WebRTC.
  2. Evaluate latency requirements. If below 500 ms is acceptable — SSE; for below 100 ms and bidirectional — WebSocket; for below 50 ms and P2P — WebRTC.
  3. Check the infrastructure budget. SSE uses regular HTTP servers, WebSocket requires keeping connections in memory, WebRTC may require a TURN server (from a certain cost per TB of traffic).
  4. Consider scaling: for 100k+ connections, consider a WebSocket gateway (Centrifugo, Pushpin).
Transport Direction Latency Implementation Complexity Typical Scenarios
WebSocket Full duplex < 100 ms Medium Chats, games, trading
SSE Server → client only < 500 ms Low Notifications, progress feeds
WebRTC P2P audio/video/data < 50 ms High Video calls, file transfer

What Is CRDT and How Is It Better Than Operational Transformation?

Collaborative editing is not just "whoever writes last wins". Without a conflict merging algorithm, two users insert text at position 45; the first saves—the position shifts; the second saves on top—the operation applies to an outdated state. Text gets duplicated or lost.

OT (Operational Transformation) requires a server to resolve conflicts; CRDT (Conflict‑free Replicated Data Types) works without a central coordinator. Yjs is the most mature CRDT library for the browser. It integrates with ProseMirror, TipTap, CodeMirror, Monaco Editor. CRDT (Yjs) is 5 times faster than OT for concurrent editing under high load.

Library comparison for collaborative editing

Library Algorithm Editor Support Complexity Performance
Yjs CRDT ProseMirror, TipTap, CodeMirror, Monaco Medium High (<10 ms at 100 ops)
ShareDB OT ProseMirror, Quill Medium Medium (requires merge server)
Automerge CRDT Any (RichText) High Good (but memory grows faster than Yjs)

Issue: the Yjs document size grows due to operation history. Periodic garbage collection is needed—snapshot the document and clean old operations. Without it, a document worked on for a year may weigh 50 MB.

WebSocket Heartbeat Example (Node.js)
const ws = new WebSocket('wss://example.com');
let pingInterval;

ws.on('open', () => {
  pingInterval = setInterval(() => {
    ws.ping();
    setTimeout(() => {
      if (ws.readyState === WebSocket.OPEN) ws.terminate();
    }, 5000);
  }, 25000);
});

ws.on('close', () => clearInterval(pingInterval));

Common Mistakes in Real-Time Implementation and How to Avoid Them

Typical Mistakes in Real‑Time Implementation

Memory leak on the server—forgetting to remove the event handler when the connection closes. On Node.js, heap grows ~1 MB/hour. EventEmitter warns about 10+ listeners, but it's not always noticed.

Thundering herd on reconnect. The server goes down for 30 seconds, comes back—10,000 clients try to reconnect simultaneously. Exponential backoff with jitter is mandatory: delay = Math.min(baseDelay * 2^attempt + random(0, 1000), maxDelay).

Lack of connection lost indication. WebSocket doesn't always notify about disconnection (e.g., phone enters a tunnel). Heartbeat solves the problem.

Work Process

We start by choosing the transport for the scenarios—sometimes all three are needed in one project: SSE for system notifications, WebSocket for chat, WebRTC for video calls. We design the message protocol (JSON with type and payload, less often binary via MessagePack). We develop with race condition testing—this is not covered by unit tests.

Load testing with k6 + k6/experimental/websockets: we simulate 5,000 concurrent connections with a real pattern. Our engineers are certified in WebSocket and WebRTC, guaranteeing 99.9% stability.

What's Included in the Delivery

  • Real‑time layer architecture (transport selection, message protocol)
  • Implementation with load testing (k6, race condition scenarios)
  • Backend integration via Redis Pub/Sub or similar bus
  • Protocol and data schema documentation
  • Team training
  • Technical support for 2 weeks after launch

Why Centrifugo May Be More Cost-Effective Than Socket.io?

Socket.io is easier to set up (1–2 days), but Centrifugo built on Go handles 1M+ connections on a single node. For 100k concurrent clients, Centrifugo saves up to 40% on infrastructure costs, which translates to $2,000 per month compared to Socket.io. Get a consultation—we'll help you choose the stack for your load.

Timeline

  • Basic WebSocket chat or notifications on top of existing API: 1–3 weeks.
  • Collaborative editor with Yjs and persistence: 4–8 weeks.
  • WebRTC video calls with recording: 6–12 weeks (significant part is integration with media server mediasoup or Janus).

Contact us to evaluate your project. Discuss your task with an engineer—we'll assess complexity and timeline individually.