LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 38 OF 42

Design a Cricket Scoreboard Like Cricinfo: LLD

A live cricket scoreboard designed and coded: match, teams, innings, overs and ball events, extras that are not legal balls, wickets and dismissal types, strike rotation, batting and bowling scorecards rebuilt from a ball-by-ball log (event sourcing), formats as a Strategy, Observer feeds, undo of a wrong ball, one writer and many readers, with full Java 17 code.

Reported atZomato

Patterns usedObserverStrategy

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 22

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 592 lines, with a small main() demo. Save it as CricketScoreboard.java, then run javac CricketScoreboard.java && java CricketScoreboard.

import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/**
 * A live cricket scoreboard. Each innings is an append-only log of events (event sourcing); totals, strike,
 * overs and both scorecards are a projection of that log. Undo removes the last event and replays.
 * One scorer writes under a lock; any number of readers take an immutable snapshot without locking.
 */
public final class CricketScoreboard {

    // ---------- formats (Strategy) ----------
    interface MatchFormat {
        String label();

        int oversPerInnings();

        int maxOversPerBowler();

        default int ballsPerOver() { return 6; }

        default boolean freeHitAfterNoBall() { return true; }
    }

    enum StandardFormat implements MatchFormat {
        T20("T20", 20, 4), ODI("ODI", 50, 10);

        private final String label;
        private final int overs;
        private final int perBowler;

        StandardFormat(String label, int overs, int perBowler) {
            this.label = label;
            this.overs = overs;
            this.perBowler = perBowler;
        }

        @Override
        public String label() { return label; }

        @Override
        public int oversPerInnings() { return overs; }

        @Override
        public int maxOversPerBowler() { return perBowler; }
    }

    /** Any other limited overs game, for example a club ten over match or a tiny demo. */
    record CustomFormat(String label, int oversPerInnings, int maxOversPerBowler) implements MatchFormat {}

    // ---------- the model: teams and events ----------
    record Team(String name, List<String> players) {
        Team {
            players = List.copyOf(players);
            if (players.size() < 2) throw new IllegalArgumentException("a team needs at least two players");
        }
    }

    enum Extra { NONE, WIDE, NO_BALL, BYE, LEG_BYE }

    enum Dismissal {
        BOWLED, CAUGHT, LBW, STUMPED, HIT_WICKET, RUN_OUT;

        boolean creditsBowler() { return this != RUN_OUT; }

        /** Which dismissals can happen on which kind of ball (only the types modelled here). */
        boolean possibleOn(Extra x) {
            return switch (x) {
                case NONE -> true;
                case WIDE -> this == STUMPED || this == RUN_OUT || this == HIT_WICKET;
                case NO_BALL, BYE, LEG_BYE -> this == RUN_OUT;
            };
        }
    }

    sealed interface Event permits OverStarted, Delivery {}

    record OverStarted(String bowler) implements Event {}

    /** One ball. runs = runs completed (or a boundary); a wide or no ball adds a one run penalty on top. */
    record Delivery(Extra extra, int runs, Dismissal out, String outBatter, String fielder) implements Event {
        static Delivery runs(int r) { return new Delivery(Extra.NONE, r, null, null, null); }

        static Delivery wide(int r) { return new Delivery(Extra.WIDE, r, null, null, null); }

        static Delivery noBall(int batRuns) { return new Delivery(Extra.NO_BALL, batRuns, null, null, null); }

        static Delivery bye(int r) { return new Delivery(Extra.BYE, r, null, null, null); }

        static Delivery legBye(int r) { return new Delivery(Extra.LEG_BYE, r, null, null, null); }

        static Delivery wicket(Dismissal how, String batter, String fielder) {
            return new Delivery(Extra.NONE, 0, how, batter, fielder);
        }

        static Delivery runOut(int completed, String batter, String fielder) {
            return new Delivery(Extra.NONE, completed, Dismissal.RUN_OUT, batter, fielder);
        }

        boolean legal() { return extra != Extra.WIDE && extra != Extra.NO_BALL; }

        int total() { return runs + (legal() ? 0 : 1); }

        int batRuns() { return extra == Extra.NONE || extra == Extra.NO_BALL ? runs : 0; }

        int bowlerRuns() { return extra == Extra.BYE || extra == Extra.LEG_BYE ? 0 : total(); }
    }

    record Logged(long seq, Instant at, Event event) {}

    // ---------- read side: immutable snapshots ----------
    record BatLine(String name, int runs, int balls, int fours, int sixes, String howOut) {
        String strikeRate() { return balls == 0 ? "-" : String.format("%.1f", runs * 100.0 / balls); }
    }

    record BowlLine(String name, int balls, int maidens, int runs, int wickets) {
        String overs() { return balls / 6 + "." + balls % 6; }

        String economy() { return balls == 0 ? "-" : String.format("%.2f", runs * 6.0 / balls); }
    }

    record Snapshot(String team, int total, int wickets, int legalBalls, int maxBalls, Integer target,
                    String striker, String nonStriker, String bowler, boolean freeHit, boolean complete,
                    int wides, int noBalls, int byes, int legByes,
                    List<BatLine> batting, List<BowlLine> bowling) {
        int extras() { return wides + noBalls + byes + legByes; }

        String overs() { return legalBalls / 6 + "." + legalBalls % 6; }

        String headline() {
            String s = team + " " + total + "/" + wickets + " (" + overs() + " ov)";
            if (target != null && !complete)
                s += ", need " + (target - total) + " from " + (maxBalls - legalBalls) + " balls";
            return s;
        }
    }

    // ---------- the projection: state rebuilt from events ----------
    static final class Bat {
        int runs, balls, fours, sixes;
        String howOut = "not out";
    }

    static final class Bowl {
        int balls, maidens, runs, wickets;
    }

    static final class InningsState {
        final Team batting;
        final Team bowling;
        final MatchFormat format;
        final Integer target;
        final Map<String, Bat> bat = new LinkedHashMap<>();
        final Map<String, Bowl> bowl = new LinkedHashMap<>();
        int total, wickets, legalBalls, wides, noBalls, byes, legByes, overRuns;
        int nextBatter = 2;
        String striker, nonStriker, bowler, lastOverBowler;
        boolean freeHit;

        InningsState(Team batting, Team bowling, MatchFormat format, Integer target) {
            this.batting = batting;
            this.bowling = bowling;
            this.format = format;
            this.target = target;
            striker = batting.players().get(0);
            nonStriker = batting.players().get(1);
            bat.put(striker, new Bat());
            bat.put(nonStriker, new Bat());
        }

        static InningsState replay(Team batting, Team bowling, MatchFormat f, Integer target,
                                   List<Logged> log) {
            InningsState s = new InningsState(batting, bowling, f, target);
            for (Logged l : log) s.apply(l.event());
            return s;
        }

        boolean complete() {
            return wickets >= batting.players().size() - 1
                    || legalBalls >= format.oversPerInnings() * format.ballsPerOver()
                    || (target != null && total >= target);
        }

        int oversBowledBy(String name) {
            Bowl b = bowl.get(name);
            return b == null ? 0 : b.balls / format.ballsPerOver();
        }

        /** Throws if the event breaks a rule; changes nothing. */
        void validate(Event e) {
            if (complete()) throw new IllegalStateException("the innings is over");
            if (e instanceof OverStarted o) {
                if (bowler != null) throw new IllegalStateException("the current over is not finished");
                if (!bowling.players().contains(o.bowler()))
                    throw new IllegalArgumentException(o.bowler() + " does not play for " + bowling.name());
                if (o.bowler().equals(lastOverBowler))
                    throw new IllegalStateException(o.bowler() + " cannot bowl two overs in a row");
                if (oversBowledBy(o.bowler()) >= format.maxOversPerBowler())
                    throw new IllegalStateException(o.bowler() + " has bowled the maximum overs");
            } else if (e instanceof Delivery d) {
                if (bowler == null) throw new IllegalStateException("start the over first: who is bowling?");
                if (d.runs() < 0 || d.runs() > 7) throw new IllegalArgumentException("runs must be 0 to 7");
                if (d.out() == null) return;
                if (!d.out().possibleOn(d.extra()))
                    throw new IllegalStateException(d.out() + " is not possible on a " + d.extra());
                if (freeHit && d.out() != Dismissal.RUN_OUT)
                    throw new IllegalStateException("free hit: only a run out can dismiss " + striker);
                if (d.out() == Dismissal.RUN_OUT) {
                    if (!d.outBatter().equals(striker) && !d.outBatter().equals(nonStriker))
                        throw new IllegalArgumentException(d.outBatter() + " is not batting");
                } else {
                    if (!d.outBatter().equals(striker))
                        throw new IllegalArgumentException("only the striker can be out " + d.out());
                    if (d.runs() != 0) throw new IllegalArgumentException("no runs count on " + d.out());
                }
            }
        }

        /** Applies one event and returns a commentary line. Used for new balls and for replay. */
        String apply(Event e) {
            int perOver = format.ballsPerOver();
            if (e instanceof OverStarted o) {
                bowler = o.bowler();
                bowl.computeIfAbsent(bowler, k -> new Bowl());
                overRuns = 0;
                return bowler + " to bowl over " + (legalBalls / perOver + 1);
            }
            Delivery d = (Delivery) e;
            // A wide or no ball keeps the same number as the ball that replaces it.
            String line = legalBalls / perOver + "." + (legalBalls % perOver + 1) + " " + bowler + " to "
                    + striker + ": " + describe(d);
            Bat b = bat.get(striker);
            Bowl w = bowl.get(bowler);
            total += d.total();
            switch (d.extra()) {
                case WIDE -> wides += d.total();
                case NO_BALL -> noBalls++;
                case BYE -> byes += d.runs();
                case LEG_BYE -> legByes += d.runs();
                case NONE -> { }
            }
            if (d.extra() != Extra.WIDE) b.balls++;   // a no ball counts as faced, a wide does not
            b.runs += d.batRuns();
            if (d.batRuns() == 4) b.fours++;         // simplification: four or six means a boundary
            if (d.batRuns() == 6) b.sixes++;
            w.runs += d.bowlerRuns();
            overRuns += d.bowlerRuns();
            if (d.legal()) {
                legalBalls++;
                w.balls++;
            }
            if (d.runs() % 2 == 1) swapEnds();         // the batters crossed: they changed ends
            if (d.out() != null) dismiss(d, w);
            freeHit = format.freeHitAfterNoBall() && (d.extra() == Extra.NO_BALL || (freeHit && !d.legal()));
            if (d.legal() && legalBalls % perOver == 0) endOver(w);
            return line;
        }

        private void dismiss(Delivery d, Bowl w) {
            wickets++;
            bat.get(d.outBatter()).howOut = howOut(d);
            if (d.out().creditsBowler()) w.wickets++;
            List<String> order = batting.players();
            String in = wickets < order.size() - 1 ? order.get(nextBatter++) : null;
            if (in != null) bat.put(in, new Bat());
            // The new batter takes the place of the batter who is out (after a catch: on strike).
            if (d.outBatter().equals(striker)) striker = in;
            else nonStriker = in;
        }

        private void endOver(Bowl w) {
            if (overRuns == 0) w.maidens++;
            lastOverBowler = bowler;
            bowler = null;    // the scorer must name the next bowler
            swapEnds();       // the next over is bowled from the other end
        }

        private void swapEnds() {
            String t = striker;
            striker = nonStriker;
            nonStriker = t;
        }

        private String howOut(Delivery d) {
            return switch (d.out()) {
                case BOWLED -> "b " + bowler;
                case CAUGHT -> "c " + d.fielder() + " b " + bowler;
                case LBW -> "lbw b " + bowler;
                case STUMPED -> "st " + d.fielder() + " b " + bowler;
                case HIT_WICKET -> "hit wicket b " + bowler;
                case RUN_OUT -> "run out (" + d.fielder() + ")";
            };
        }

        static String describe(Delivery d) {
            String what = switch (d.extra()) {
                case NONE -> d.runs() == 4 ? "FOUR" : d.runs() == 6 ? "SIX" : plural(d.runs(), "run");
                case WIDE -> "wide" + (d.runs() > 0 ? " + " + plural(d.runs(), "run") : "");
                case NO_BALL -> "no ball" + (d.runs() > 0 ? " + " + plural(d.runs(), "run") : "");
                case BYE -> plural(d.runs(), "bye");
                case LEG_BYE -> plural(d.runs(), "leg bye");
            };
            if (d.out() == null) return what;
            String out = "OUT! " + d.outBatter() + " " + d.out().name().toLowerCase().replace('_', ' ');
            return d.runs() == 0 && d.extra() == Extra.NONE ? out : what + ", " + out;
        }

        private static String plural(int n, String word) {
            return (n == 0 ? "no" : String.valueOf(n)) + " " + word + (n == 1 ? "" : "s");
        }

        Snapshot snapshot() {
            List<BatLine> bl = new ArrayList<>();
            bat.forEach((n, x) -> bl.add(new BatLine(n, x.runs, x.balls, x.fours, x.sixes, x.howOut)));
            List<BowlLine> wl = new ArrayList<>();
            bowl.forEach((n, x) -> wl.add(new BowlLine(n, x.balls, x.maidens, x.runs, x.wickets)));
            return new Snapshot(batting.name(), total, wickets, legalBalls,
                    format.oversPerInnings() * format.ballsPerOver(), target, striker, nonStriker, bowler,
                    freeHit, complete(), wides, noBalls, byes, legByes, List.copyOf(bl), List.copyOf(wl));
        }
    }

    // ---------- Observer ----------
    enum UpdateKind { BALL, OVER_END, CORRECTION, INNINGS_END }

    record Update(UpdateKind kind, String text, Snapshot snapshot) {}

    interface ScoreListener {
        void onUpdate(Update u);
    }

    // ---------- the match: single writer, many readers ----------
    static final class Innings {
        final Team batting;
        final Team bowling;
        final Integer target;
        final List<Logged> log = new ArrayList<>();
        InningsState state;

        Innings(Team batting, Team bowling, Integer target, InningsState state) {
            this.batting = batting;
            this.bowling = bowling;
            this.target = target;
            this.state = state;
        }
    }

    static final class Match {
        private final MatchFormat format;
        private final Supplier<Instant> clock;
        private final List<Innings> innings = new ArrayList<>();
        private final List<ScoreListener> listeners = new CopyOnWriteArrayList<>();
        private volatile Snapshot latest;   // the only thing readers touch
        private long seq;

        Match(MatchFormat format, Supplier<Instant> clock) {
            this.format = format;
            this.clock = clock;
        }

        void subscribe(ScoreListener l) { listeners.add(l); }

        /** Lock free: always a complete, immutable picture. */
        Snapshot snapshot() { return latest; }

        synchronized void startInnings(Team batting, Team bowling) {
            if (innings.size() == 2) throw new IllegalStateException("both innings are done");
            Integer target = null;
            if (!innings.isEmpty()) {
                if (!current().state.complete()) throw new IllegalStateException("first innings still on");
                target = current().state.total + 1;
            }
            InningsState fresh = new InningsState(batting, bowling, format, target);
            innings.add(new Innings(batting, bowling, target, fresh));
            latest = current().state.snapshot();
        }

        synchronized void startOver(String bowler) { append(new OverStarted(bowler)); }

        synchronized void record(Delivery d) { append(d); }

        private void append(Event e) {
            Innings i = current();
            i.state.validate(e);                             // a bad entry throws before anything changes
            i.log.add(new Logged(++seq, clock.get(), e));    // the log is the source of truth
            String text = i.state.apply(e);
            Snapshot s = i.state.snapshot();
            latest = s;                                      // volatile write: safe publication
            if (e instanceof Delivery) {
                fire(new Update(UpdateKind.BALL, text, s));
                if (i.state.bowler == null) fire(new Update(UpdateKind.OVER_END, "end of over", s));
                if (s.complete()) fire(new Update(UpdateKind.INNINGS_END, "innings over", s));
            }
        }

        /** Correct a wrong entry: drop the last event and rebuild the state by replaying the log. */
        synchronized Event undo() {
            Innings i = current();
            if (i.log.isEmpty()) throw new IllegalStateException("nothing to undo");
            Logged last = i.log.remove(i.log.size() - 1);
            String label = last.event() instanceof Delivery d ? InningsState.describe(d) : "over start";
            i.state = InningsState.replay(i.batting, i.bowling, format, i.target, i.log);
            latest = i.state.snapshot();
            fire(new Update(UpdateKind.CORRECTION, "correction: removed " + label, latest));
            return last.event();
        }

        synchronized List<Logged> log(int index) { return List.copyOf(innings.get(index).log); }

        /** Event sourcing check: a fresh replay must give exactly the live snapshot. */
        synchronized boolean replayMatches(int index) {
            Innings i = innings.get(index);
            return InningsState.replay(i.batting, i.bowling, format, i.target, i.log).snapshot()
                    .equals(i.state.snapshot());
        }

        synchronized String result() {
            if (innings.size() < 2 || !current().state.complete()) return "in progress";
            InningsState first = innings.get(0).state;
            InningsState chase = innings.get(1).state;
            if (chase.total >= chase.target) {
                int inHand = chase.batting.players().size() - 1 - chase.wickets;
                return chase.batting.name() + " won by " + inHand + " wickets";
            }
            if (chase.total == chase.target - 1) return "match tied";
            return first.batting.name() + " won by " + (chase.target - 1 - chase.total) + " runs";
        }

        private Innings current() {
            if (innings.isEmpty()) throw new IllegalStateException("no innings started");
            return innings.get(innings.size() - 1);
        }

        // Called under the lock so updates arrive in order; a slow listener should queue and return.
        private void fire(Update u) { for (ScoreListener l : listeners) l.onUpdate(u); }
    }

    // ---------- listeners for the demo ----------
    static final class Commentary implements ScoreListener {
        @Override
        public void onUpdate(Update u) {
            if (u.kind() == UpdateKind.BALL)
                System.out.println("  " + u.text() + (u.snapshot().freeHit() ? "  [FREE HIT next]" : ""));
            else if (u.kind() == UpdateKind.CORRECTION) System.out.println("  ** " + u.text());
        }
    }

    static final class ScoreboardView implements ScoreListener {
        @Override
        public void onUpdate(Update u) {
            if (u.kind() == UpdateKind.OVER_END || u.kind() == UpdateKind.INNINGS_END)
                System.out.println("  [scoreboard] " + u.text() + ": " + u.snapshot().headline());
        }
    }

    // ---------- demo ----------
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    static void expectRejected(Runnable action) {
        try {
            action.run();
            throw new AssertionError("should have been rejected");
        } catch (IllegalArgumentException | IllegalStateException e) {
            System.out.println("  Rejected: " + e.getMessage());
        }
    }

    static boolean consistent(Snapshot s) {
        int batRuns = s.batting().stream().mapToInt(BatLine::runs).sum();
        int bowlRuns = s.bowling().stream().mapToInt(BowlLine::runs).sum();
        int balls = s.bowling().stream().mapToInt(BowlLine::balls).sum();
        return batRuns + s.extras() == s.total() && bowlRuns + s.byes() + s.legByes() == s.total()
                && balls == s.legalBalls();
    }

    static void printScorecard(Snapshot s) {
        System.out.println("Scorecard: " + s.headline());
        for (BatLine b : s.batting())
            System.out.printf("  %-5s %-16s %3d (%d) 4s:%d 6s:%d SR %s%n", b.name(), b.howOut(), b.runs(),
                    b.balls(), b.fours(), b.sixes(), b.strikeRate());
        System.out.println("  Extras " + s.extras() + " (w " + s.wides() + ", nb " + s.noBalls() + ", b "
                + s.byes() + ", lb " + s.legByes() + ")");
        for (BowlLine w : s.bowling())
            System.out.printf("  %-5s %s-%d-%d-%d  econ %s%n", w.name(), w.overs(), w.maidens(), w.runs(),
                    w.wickets(), w.economy());
    }

    public static void main(String[] args) throws Exception {
        AtomicReference<Instant> time = new AtomicReference<>(Instant.parse("2026-03-14T14:00:00Z"));
        Supplier<Instant> clock = () -> time.updateAndGet(t -> t.plusSeconds(40)); // fake: 40 s per event
        Team falcons = new Team("Falcons",
                List.of("Aru", "Bex", "Cato", "Dua", "Eli", "Finn", "Gus", "Hari", "Ivo", "Jai", "Kit"));
        Team tigers = new Team("Tigers",
                List.of("Lev", "Mo", "Nia", "Oz", "Pia", "Quin", "Ray", "Sol", "Tam", "Uma", "Vik"));
        for (StandardFormat f : StandardFormat.values())
            System.out.println(f.label() + ": " + f.oversPerInnings() + " overs, at most "
                    + f.maxOversPerBowler() + " per bowler");

        Match m = new Match(new CustomFormat("Two over demo", 2, 1), clock);
        m.subscribe(new Commentary());
        m.subscribe(new ScoreboardView());

        System.out.println("Innings 1: Falcons bat");
        m.startInnings(falcons, tigers);
        expectRejected(() -> m.record(Delivery.runs(1)));                    // nobody is bowling yet
        m.startOver("Lev");
        m.record(Delivery.runs(1));                                          // odd: Bex now on strike
        m.record(Delivery.wide(0));                                          // not a legal ball
        m.record(Delivery.runs(4));
        m.record(Delivery.noBall(2));                                        // free hit next
        expectRejected(() -> m.record(Delivery.wicket(Dismissal.CAUGHT, "Bex", "Nia")));
        m.record(Delivery.runs(4));                                          // typed wrong: it was a six
        m.undo();
        m.record(Delivery.runs(6));
        m.record(Delivery.wicket(Dismissal.BOWLED, "Bex", null));            // Cato walks in on strike
        m.record(Delivery.bye(1));
        m.record(Delivery.runs(2));                                          // sixth legal ball: over ends
        expectRejected(() -> m.startOver("Lev"));
        m.startOver("Mo");
        m.record(Delivery.wicket(Dismissal.CAUGHT, "Cato", "Oz"));
        m.record(Delivery.runs(1));
        m.record(Delivery.runOut(1, "Dua", "Pia"));                         // one run done, then run out
        m.record(Delivery.runs(4));
        m.record(Delivery.runs(0));
        m.record(Delivery.runs(1));
        Snapshot first = m.snapshot();
        printScorecard(first);
        check(first.total() == 25 && first.wickets() == 3 && first.extras() == 3, "first innings total");
        check(consistent(first), "scorecards add up");
        BowlLine lev = first.bowling().get(0);
        BowlLine mo = first.bowling().get(1);
        check(lev.runs() == 17 && lev.wickets() == 1 && mo.runs() == 7 && mo.wickets() == 1, "bowling card");
        check(m.replayMatches(0), "a fresh replay gives the same scoreboard");
        List<Logged> log = m.log(0);
        System.out.println("Log: " + log.size() + " events, " + log.get(0).at() + " to "
                + log.get(log.size() - 1).at());

        System.out.println("Innings 2: Tigers need 26");
        m.startInnings(tigers, falcons);
        m.startOver("Gus");
        m.record(Delivery.runs(6));
        m.record(Delivery.runs(6));
        m.record(Delivery.legBye(1));
        m.record(Delivery.runs(4));
        m.record(Delivery.runs(4));
        m.record(Delivery.runs(1));
        m.startOver("Hari");
        m.record(Delivery.runs(4));                                          // target reached
        expectRejected(() -> m.record(Delivery.runs(1)));
        System.out.println("Result: " + m.result());
        check(m.result().equals("Tigers won by 10 wickets"), "result");

        // One scorer writes a whole T20 innings while three readers check every snapshot they see.
        Match live = new Match(StandardFormat.T20, clock);
        live.startInnings(falcons, tigers);
        AtomicBoolean done = new AtomicBoolean();
        AtomicInteger inconsistent = new AtomicInteger();
        ExecutorService readers = Executors.newFixedThreadPool(3);
        List<Future<?>> jobs = new ArrayList<>();
        for (int r = 0; r < 3; r++)
            jobs.add(readers.submit(() -> {
                do {
                    if (!consistent(live.snapshot())) inconsistent.incrementAndGet();
                } while (!done.get());
            }));
        int[] pattern = {1, 0, 4, 2, 0, 6};
        List<String> attack = List.of("Lev", "Mo", "Nia", "Oz", "Pia");      // four overs each, never twice
        for (int over = 0; over < 20; over++) {
            live.startOver(attack.get(over % attack.size()));
            if (over % 4 == 3) live.record(Delivery.wide(0));
            for (int b = 0; b < 6; b++) live.record(Delivery.runs(pattern[(over + b) % 6]));
        }
        done.set(true);
        for (Future<?> f : jobs) f.get();
        readers.shutdown();
        Snapshot end = live.snapshot();
        System.out.println("T20 with 3 live readers: " + end.headline() + ", inconsistent snapshots: "
                + inconsistent.get());
        check(end.total() == 265 && end.complete() && inconsistent.get() == 0, "single writer, many readers");
        check(live.replayMatches(0), "replay of a full innings");
    }
}

Notes

Requirements

Fix the scope. A limited overs match has two teams and two innings. An over is six legal balls. The scorer records runs, extras such as wides, no balls, byes and leg byes, and wickets with the way the batter got out. The strike changes after odd runs and at the end of each over. We show batting and bowling scorecards, support T20 and one day formats, let the scorer correct a wrong entry, and push updates to many viewers.

Ask the questions that change the code. Does a wide count as one of the six balls? No: it gives one run and is bowled again. A no ball also gives one run, and in limited overs cricket the next ball is a free hit. Does a run out count in the bowler's wickets? No, the other dismissals do. A bowler can never bowl two overs in a row, and can bowl at most four overs in a T20 and ten in a one day match. Test matches and rain rules are out of scope.

Requirements
  • two teams, two innings
  • overs of six legal balls
  • runs, wides, no balls, byes,
  • leg byes
  • wickets with how out
  • strike changes on odd runs and
  • at the end of an over
  • batting and bowling scorecards
  • formats: T20, ODI
  • fix a wrongly entered ball
  • live feeds for many viewers
Clarify first
  • does a wide count as a ball?
  • no: one run, ball bowled again
  • no ball: one run, free hit next
  • run out counts for the bowler?
  • no, the other ways do
  • same bowler two overs in a row?
  • never
  • overs per bowler: T20 four,
  • ODI ten
  • out of scope: Test matches,
  • rain rules, ball tracking

Entities

Underline the nouns: match, team, player, innings, over, ball, wicket. A match has two teams, a format and up to two innings. A team is a name and a batting order. Here is the key insight: an over and a scorecard are not things you store. An innings is just a list of events in order, and overs, totals and scorecards are all computed from that list. Players are names in this version, so a player is not even a class yet.

Class diagram

Get the extras right, because interviewers who know cricket will check. A normal ball gives its runs to the batter. A wide adds one run plus any runs taken, is not a legal ball, does not count as a ball faced, and is charged to the bowler. A no ball adds one run, is not a legal ball, but does count as faced, and runs hit off it go to the batter. Byes and leg byes are legal balls whose runs are extras and are not charged to the bowler.

In code, a ball is a Delivery record: the kind of extra, the runs completed, and an optional dismissal with the batter who is out. Four short methods hold all the rules: is it legal, the total it adds, the runs credited to the batter, and the runs charged to the bowler. Events form a sealed interface with two kinds: a delivery, and an over started by a named bowler. Records never change, which matters later for readers.

What each ball means
  • normal: runs to the batter
  • wide: +1, not a legal ball,
  • not faced, bowler charged
  • no ball: +1, not legal, faced,
  • bat runs go to the batter
  • bye, leg bye: legal ball,
  • runs are extras, not the
  • bowler's fault
  • legal ball: counts in the over
Delivery record
record Delivery(Extra extra, int runs,
    Dismissal out, String outBatter, ..)
  boolean legal()  // not WIDE, not NO_BALL
  int total()      // runs, +1 if not legal
  int batRuns()    // NONE, NO_BALL only
  int bowlerRuns() // all but byes

sealed interface Event
  permits OverStarted, Delivery

Event sourcing

This is event sourcing. The ball-by-ball log is the single source of truth, and it only grows. An InningsState object is a projection: it starts empty and applies events one at a time, keeping the total, wickets, legal balls, who is on strike, who is bowling, and every scorecard row. For a new ball we apply just that one event. But at any moment we could throw the state away, replay the log, and get exactly the same scoreboard. That property gives us undo almost for free.

Event sourcing
  • the log: append-only events
  • InningsState: apply(event)
  • total, wickets, balls,
  • striker, bowler, free hit,
  • every scorecard row
  • new ball: validate, append,
  • apply one event
  • any time: replay the log from
  • empty and get the same state

Strategy: format

Formats differ in their limits, so the format is a Strategy. The MatchFormat interface answers four questions: overs per innings, the most overs one bowler may bowl, balls per over, and whether a no ball gives a free hit. T20 is twenty overs and four per bowler; a one day match is fifty and ten. A club's ten over game is just a custom record. The innings code asks the format and never checks a format name.

MatchFormat
interface MatchFormat {
  int oversPerInnings();
  int maxOversPerBowler();
  default int ballsPerOver() { return 6; }
  default boolean freeHitAfterNoBall()
      { return true; }
}
enum StandardFormat implements ..
  T20(20, 4), ODI(50, 10)
record CustomFormat(..) for a
  ten over game or a test run

Flow: record a ball

Walk the main flow. The scorer records a four. First the state validates it: is there an over in progress, is the innings still alive, is this dismissal possible on this kind of ball? A bad entry throws before anything changes. Then the event is appended to the log with a time from an injected clock, applied to the state, and a fresh immutable snapshot is published. Finally listeners hear about the ball, and about the end of an over or innings.

record(delivery)
synchronized void record(Delivery d) {
  state.validate(d);  // throws, no change
  log.add(new Logged(seq, clock.get(), d));
  String text = state.apply(d);
  latest = state.snapshot(); // volatile
  notify(BALL, text);
  if (over ended) notify(OVER_END);
  if (innings done) notify(INNINGS_END);
}

Strike rotation

Strike rotation is where most solutions break. If the batters complete an odd number of runs they have changed ends, so we swap the striker and the non-striker. This uses runs actually run, so a wide with one run taken also swaps. After the sixth legal ball the over ends: the bowler gets a maiden if the over cost them nothing, the bowler slot is cleared so the scorer must name the next bowler, and the ends swap again, because the next over is bowled from the other end.

Who faces the next ball?
// runs actually completed, even on
// a wide, bye or leg bye
if (d.runs() % 2 == 1) swapEnds();
if (d.out() != null) dismiss(d);
if (d.legal() && legalBalls % 6 == 0) {
  if (overRuns == 0) bowler.maidens++;
  lastOverBowler = bowler;
  bowler = null;  // must start a new over
  swapEnds();
}

Wickets

Wickets have rules too. Bowled, caught, leg before, stumped and hit wicket go into the bowler's wicket column; a run out does not, and either batter can be run out. Off a wide, only stumped, run out or hit wicket are possible. Off a no ball, or on a free hit, the striker can only be run out among our types. The next batter in the order walks in and takes the place of the batter who is out, so after a catch the new batter faces the next ball.

Dismissal rules
  • bowled, caught, lbw, stumped,
  • hit wicket: bowler credited
  • run out: not the bowler's
  • wicket; either batter
  • on a wide: stumped, run out,
  • hit wicket only
  • on a no ball: run out only
  • free hit: run out only
  • new batter takes the place of
  • the batter who is out

Scorecards

The scorecards fall out of the replay. Each batter has runs, balls faced, fours, sixes and how they got out, and the strike rate is runs times one hundred divided by balls. Each bowler has overs, maidens, runs conceded and wickets, and the economy is runs per six balls. Overs are written like three point four, meaning three overs and four balls. A neat check: batters' runs plus extras equals the total, which also equals bowlers' runs plus byes and leg byes.

Derived numbers
  • batter: runs, balls, 4s, 6s,
  • how out
  • strike rate: runs x 100 / balls
  • bowler: overs, maidens, runs,
  • wickets
  • overs shown as 3.4: three overs
  • and four balls
  • economy: runs x 6 / balls
  • check: bat runs + extras =
  • total = bowler runs + byes

Observer: live feeds

Live feeds use the Observer pattern. Each update carries a kind, a line of text such as nought point three, four runs, and the new snapshot. The commentary listener prints every ball. The scoreboard view only cares about the end of each over. A push notifier for wickets, or a feed to a TV graphics system, is one more listener. The match never knows who is listening, and the list is copy-on-write so subscribing never blocks the scorer.

Observer
enum UpdateKind { BALL, OVER_END,
  CORRECTION, INNINGS_END }
record Update(kind, text, snapshot)
interface ScoreListener {
  void onUpdate(Update u);
}
listeners: CopyOnWriteArrayList

Commentary: every BALL line
ScoreboardView: OVER_END only

Undo a wrong ball

The scorer typed a four, but it was a six. How do we fix it? A naive design writes reverse logic for every case: take back the runs, swap the strike back, un-end the over, restore the free hit. That is a bug farm. With event sourcing we simply remove the last event and replay the log from the start. A full T20 innings is a few hundred events, so replay takes microseconds, and the result is correct by construction.

undo()
synchronized Event undo() {
  Logged last = log.remove(size - 1);
  state = InningsState.replay(log);
  latest = state.snapshot();
  notify(CORRECTION, ..);
  return last.event();
}

replay of a whole T20 innings:
  a few hundred events, microseconds

Concurrency

Concurrency here has a clear shape: one writer, many readers. Writes are synchronized on the match, but only the scorer writes, so the lock is never contended. The mutable state is never handed out. After each write we build an immutable snapshot of records and copied lists, and publish it through a volatile field. Readers just read that field, with no lock at all, and can never see a half-applied ball, such as runs added but the strike not yet swapped.

Check every shared thing. The log and the state are touched only while holding the match lock. Snapshots are immutable and published through a volatile field. Listeners live in a copy-on-write list. We call them in order while holding the lock, so commentary lines never arrive out of order; a slow listener, like one that sends push messages, should put the update on its own queue and return quickly. Events are records, so they are safe to share anywhere.

Single writer, many readers
  • writes: synchronized on Match
  • only the scorer, so no fight
  • state: mutable, never shared
  • snapshot: records + List.copyOf
  • built under the lock
  • published through a volatile
  • field: safe publication
  • readers: no lock, never see a
  • half-applied ball
Thread safety checklist
  • log + state: only under the
  • Match lock
  • snapshot: immutable, volatile
  • listeners: CopyOnWriteArrayList
  • listeners called in order under
  • the lock: slow ones hand off
  • to their own queue
  • fake clock: AtomicReference
  • events: records, safe to share

Chase and result

The second innings gets a target: the first innings total plus one. An innings ends in three ways: ten wickets fall, the overs run out, or the chasing side reaches the target. After that the state rejects any more balls. The result follows the cricket convention: a team that chases successfully wins by the wickets it has left, a team that defends wins by the runs it was ahead, and equal scores are a tie.

When an innings ends
boolean complete() {
  return wickets >= players - 1
      || legalBalls >= overs * 6
      || (target != null
          && total >= target);
}
target = first innings total + 1
chase won: by wickets in hand
chase lost: by runs short
equal scores: a tie

Extensibility

Interviewers will push on extensions. A Test match needs a format with no over limit, plus declarations and the follow-on. A super over is a short third innings. Partnerships, fall of wickets, or runs per over for a chart are each just another projection over the same log, with no change to how balls are recorded. Rain-reduced targets are a target strategy. A win predictor is another listener. The event log makes most of these cheap.

Extension points
  • Test match: format with no over
  • limit, follow-on, declarations
  • super over: a third mini innings
  • fielders and keepers: a Player
  • class with roles
  • partnerships, fall of wickets:
  • one more projection of the log
  • rain rules: a TargetStrategy
  • win prediction: a listener

Testing

The full code is below the player. The demo uses a two over custom format so every rule shows up in a few lines: a wide that is not a legal ball, a no ball and its free hit, a catch rejected on the free hit, a wrong four corrected to a six with undo, a bowled, a bye, a catch, a run out, and a bowler blocked from bowling twice in a row. Then the chase, the result, and a T20 innings written while three reader threads check every snapshot.

Run it
0.3 Lev to Bex: no ball + 2 runs
  [FREE HIT next]
Rejected: free hit: only a run out
0.3 Lev to Bex: FOUR
** correction: removed FOUR
0.3 Lev to Bex: SIX
Rejected: Lev cannot bowl two overs
  in a row
Falcons 25/3 (2.0 ov)
Tigers won by 10 wickets

Follow-ups

Expect follow-ups. With millions of viewers, the snapshot or each event goes to a publish and subscribe system and is cached at the edge, so viewers never touch the scorer's server. If the scorer's device goes offline, it queues events with sequence numbers and sends them later. If two scorers type at once by mistake, the server rejects an event whose sequence number is stale. And why not just store totals? Totals drift with corrections; the log does not.

Follow-ups to expect
  • millions of viewers?
  • push snapshots to a pub-sub,
  • cache at the edge
  • scorer phone goes offline?
  • queue events, sequence numbers
  • two scorers by mistake?
  • reject a stale sequence
  • why not store the totals?
  • they drift; the log never lies
  • audit: who changed which ball

Say it like this

Here is the short version to say out loud. An innings is an append-only log of balls. Totals, strike, overs and both scorecards are a projection: apply each new event, or replay the log to undo a mistake. Over and bowler limits come from a format strategy, live feeds are observers, and one scorer writes under a lock while any number of readers take an immutable snapshot published through a volatile field.

In the interview
  • "An innings is an append-only
  • log of balls. Totals, strike,
  • overs and scorecards are a
  • projection: apply each event,
  • or replay to undo. Formats are
  • a Strategy, feeds are
  • observers, one scorer writes
  • under a lock and readers get an
  • immutable volatile snapshot."

Interview questions

Why store a ball-by-ball log instead of updating totals directly?

The log is the source of truth and every number on the scoreboard is derived from it, so totals can never drift from what happened. It also gives undo, audit and new statistics for free: remove an event and replay, or write a new projection over the same events.

How do you undo a wrongly entered ball?

Remove the last event from the log and rebuild the innings state by replaying the remaining events from the start. This avoids hand-written reverse logic for runs, strike, over ends and free hits, and a full innings is only a few hundred events, so replay is cheap.

How do wides and no balls differ in the scoring logic?

Both add a one run penalty and neither counts as one of the six legal balls in the over. A wide is not counted as a ball faced and all its runs are wides, while a no ball is counted as faced and runs hit off it go to the batter. Both are charged to the bowler.

When does the strike change?

When the batters complete an odd number of runs, including runs taken off a wide, bye or leg bye, and again at the end of every over. A boundary four or six is even, so it does not swap. Applying the odd-run swap before handling a run out lets the scorer name whichever batter was run out.

Which dismissals count for the bowler, and which are allowed on extras?

Bowled, caught, leg before wicket, stumped and hit wicket are credited to the bowler; a run out is not. Off a wide, the striker can be stumped, run out or out hit wicket; off a no ball or on a free hit, among these types only a run out is possible.

Why model the match format as a Strategy?

Formats differ only in their limits: overs per innings, overs per bowler and free hit rules. Putting them behind a MatchFormat interface keeps the innings code free of format checks, and adding a new format is a new enum value or record rather than an edit to the scoring logic.

How do many readers see consistent scores while the scorer writes?

The scorer is the single writer and updates the state under a lock. After each write it builds an immutable snapshot and publishes it through a volatile field, so readers read lock free and always see a complete, consistent state, never a half-applied ball.

How would you push live updates to millions of viewers?

Use the Observer pattern inside the service, and have one listener publish each event or snapshot to a pub-sub topic. Edge caches and websocket gateways fan it out to viewers, so the scoring service only handles one writer and a few subscribers.

How do you compute strike rate and economy?

Strike rate is runs scored times one hundred divided by balls faced, where no balls count as faced and wides do not. Economy is runs conceded divided by overs bowled, computed as runs times six divided by legal balls; byes and leg byes are not charged to the bowler.