Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 133 ยท Projects

Project: Real-Time Polling and Auction

Build live polls and a bidding auction in Node.js. Pure rule classes, a WebSocket hub that broadcasts every change to all viewers, anti-sniping time extension and clean validation.

Some pages should never need a refresh: a live vote tally during a talk, the current price in an online auction, the scoreboard of a game. When one person acts, everyone watching sees the change within a fraction of a second. That is the job of WebSockets, a persistent two-way connection between browser and server (the WebSockets lesson explains the protocol).

In this project you build two real-time features on the same foundation: a poll (one vote per person, live results) and an auction (bids must beat the current price, the clock can extend when someone bids at the last second). The most important design decision is to keep the rules in plain classes that know nothing about sockets, and put a thin hub around them that receives messages and broadcasts the new state. Rules are easy to test; sockets are not.

Plan

  1. Poll and Auction: pure logic with an injected clock. They throw a RuleError for invalid actions.
  2. Hub: holds the rooms (one poll or auction each), the connected clients, and does the broadcasting.
  3. A small WebSocket server: handshake, frame parsing (text frames only) and JSON messages.
  4. Clients using Node's built-in WebSocket.

Messages are JSON objects such as {"type":"bid","amount":120} from the client and {"type":"state", ...} or {"type":"error", ...} from the server. A text protocol like this is easy to log and debug.

Stage 1: the rules, without any network

Start with the poll. The rules are short: the options are fixed when the poll is created, each voter can vote once (you may allow changing the vote), and unknown options are rejected. The voter is identified by an id the server decides (here a connection id); never trust a voter id sent by the client in a real system, or one person could vote a hundred times.

Node.js Poll: validation, one vote per voter, live results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The poll counts, the results are derived from the votes on demand, and every invalid action is a RuleError with a short machine-readable code. The hub will turn a RuleError into an error message for that one client, and anything else into a generic failure.

An auction has more rules, and they involve time. The clock is passed in, so tests can move it forward without waiting.

  • The auction has a start price, a minimum increment and an end time.
  • A bid must be at least current + increment (or the start price for the first bid).
  • The seller or current leader cannot bid against themselves.
  • Bids after the end time are rejected, and close() reports the winner.
  • Anti-sniping: a bid in the last extendWindowMs pushes the end time out by extendByMs. Without this rule people wait until the last second to bid, and nobody has a chance to answer.
Node.js Auction: increments, deadline and anti-sniping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the anti-sniping line: Ana's bid at 55 seconds came within 10 seconds of the end, so the end moved to 65 seconds and msLeft shows 10,000. Ben's bid at 70 seconds is refused, and result() names the winner. Because Auction takes now as a parameter, this whole story ran in a few milliseconds with exactly repeatable output.

Money amounts should be integers in the smallest unit (cents), never floating-point numbers: 0.1 + 0.2 is not 0.3. The code above uses whole numbers for that reason, and rejects anything else.

Stage 2: the hub that broadcasts

The hub knows about rooms and connections, but nothing about WebSocket frames. A connection is just an object with a send(text) method, so the hub can be tested with fake connections. Its job for each incoming message is the same every time:

  1. Parse the JSON; reject malformed messages.
  2. Find the room, ask the rule object to apply the action, catching RuleError.
  3. On success, broadcast the new state to everyone in the room. On failure, send an error only to the sender.

Broadcasting the whole (small) state after every change is the simplest correct design. Clients never have to merge partial updates, and a client that connects late gets the current state in one message.

Node.js The Hub, tested with fake connections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at who received what. Both clients saw the state after each successful vote, but only b got already-voted, and only a got bad-json and unsupported. The hub never lets a client crash it: malformed JSON and rule violations become error messages. Only RuleError is converted; any other exception is a real bug and is rethrown instead of being hidden.

Stage 3: put it on real WebSockets

Node ships a WebSocket client but no server, so we reuse the small hand-written server from the WebSockets lesson, reduced to text frames. In production you would use the ws package, which does the same job with all the edge cases handled; the hub does not care which one delivers the messages. The final program runs both rooms: a poll and an auction, three browsers (here, three WebSocket clients) and a manual clock.

Node.js Live poll and auction over WebSockets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every bid produced a state message for both bidders, the under-increment bid produced an error for Ben only, and Cy's poll room is completely separate: Cy never sees auction prices. A bid that arrives after the deadline is refused by the rules, because the clock lives in the rule object and not in the socket code.

Hardening checklist

  • Authentication. The connection id here is created by the server. Real voters and bidders sign in first (a cookie or a token in the Sec-WebSocket-Protocol or the first message), and the user id from the session replaces conn.id.
  • Validate everything. The hub checks types; add size limits for messages and a rate limit per connection (see Rate Limiting).
  • Concurrency. All rules run on one thread and each message is handled completely before the next, so two bids never interleave. With several server processes you need a shared store and atomic updates, or you route each auction to a single process.
  • Persistence. Keep bids and votes in a database, so a restart does not erase an auction; the rule objects can be rebuilt from stored bids.
  • Reconnects. Clients should reconnect and join again; the first message after joining is the current state, so nothing is lost (reconnecting clients).
  • Scaling out. Broadcasting across processes needs a pub/sub channel such as Redis; see Scalability Patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are the poll and auction rules kept in classes that know nothing about sockets?

    Separating rules from transport means a test can call bid() directly with a fake clock. The hub is only plumbing around well-tested logic.
  2. 2. What does the anti-sniping rule do?

    Without it, a bid in the final second wins before anyone can respond. Extending the deadline gives others a fair chance.
  3. 3. After a successful bid the hub sends the state to every member of the room, but an invalid bid produces an error message for only one client. Why?

    A successful action changes shared state that everybody displays. A rejected action changes nothing, so only the person who made the mistake needs to hear about it.
  4. 4. Why does the hub rethrow exceptions that are not RuleError?

    Expected rule violations are reported to the client. Anything else means the program is wrong and should surface in logs or monitoring, not disappear into an error message.
  5. 5. Why should the voter or bidder id come from the server and not from the message?

    Anything the client sends can be forged. The server decides who a connection is, usually from the session, and only then applies the rules.

Summary

  • Keep game rules in pure classes with an injected clock; throw a dedicated RuleError for invalid actions.
  • A hub maps JSON messages to rule calls, broadcasts the whole new state to a room after success, and sends errors only to the sender.
  • Anti-sniping and minimum increments are small rules with a big effect on fairness; use integers for money.
  • Node has a WebSocket client built in but needs a small server or the ws package; the hub works with either.
  • Real deployments add authentication, rate limits, persistence, reconnect logic and a pub/sub layer to scale across processes.

Next: Project: Blog and Social API with Auth