Brahim Benzartifor

Candidate submission · Software Engineer exercise

Taps in.
Trips out.

The Java fare engine I wrote for your exercise, running live in this page. Pick a card, tap the reader, drive the bus.

80
tests passing
0
lines rewritten in JS
<1 ms
to re-price a day
Loading engine…

5500 00•• •••• 5559

BRAHIM BENZARTI
Card
$7.30$3.25$5.50123

Tap on, then pick a stop to ride to.

22-01-2026 08:00:00 UTC
Charged today
  1. No taps yet. Tap on, drive to another stop, tap off.
Taps sent to the engine (0)

A blue city bus passing at speed

The reader lets you on.The price comes later.

  1. Tap onThe bus is often offline. The reader only checks the card is real.
  2. Tap offTwo taps on one bus make a trip. One tap alone pays the highest fare.
  3. ChargeThe fare is worked out afterwards. That is the code on this page.
1.0 Match

Six taps, three trips, one unmatched tap.

The brief's sample, taken apart the way TripPricer does it.

  1. Keep scrolling: the taps sort themselves
122-01-2026 13:00:00ONStop1Bus37··5559
222-01-2026 13:05:00OFFStop2Bus37··5559
322-01-2026 09:20:00ONStop3Bus36··1111
423-01-2026 08:00:00ONStop1Bus37··1111
523-01-2026 08:02:00OFFStop1Bus37··1111
624-01-2026 16:30:00OFFStop2Bus37··5559
2.0 Price

Bring your own taps.

Edit the CSV or the fares and the engine re-runs as you type. Each rule I had to decide comes with a scenario that proves it.

Total charged$0.00
StartedFromToSecsChargeStatusCardTariff

    Rules the brief left open

    1. Taps are ordered by their own timestamp, never by when they arrived.

    2. A tap off with nothing to pair it with is reported, not charged.

    3. A second tap on leaves the first trip incomplete, at the highest fare from its stop.

    4. A tap on and a tap off are only a trip when they share a bus and an operator.

    5. Tap on and off at the same stop: cancelled, $0.00, with the tap off kept.

    6. A tap resent unchanged is kept once. The copy is reported.

    7. An ID reused with different data: neither copy is trusted, so arrival order can't change the price.

    8. A trip touching a stop the tariff doesn't know is reported, never charged a maximum fare.

    9. New fares are a new dated tariff. A trip is priced by the one in force when it began.

    10. Each operator brings its own stops, fares and rule for incomplete trips.

    3.0 Change

    New fares are added, never edited.

    A tariff has a start date. A trip uses the one in force when the passenger tapped on, so last month's trips price the same forever.

    c1-2026-01January fares
    • Stop1 → Stop2$3.25
    • Stop2 → Stop3$5.50
    • Stop1 → Stop3$7.30
    c1-2026-02February fares
    • Stop1 → Stop2$3.50
    • Stop2 → Stop3$5.90
    • Stop1 → Stop3$7.80
    Stop1 → Stop3, a 25 minute ridepriced with

    Scroll to move the trip past midnight

    Re-run January

    Ten January trips, priced with the catalogue as it was then and with today's, which has February's fares and a second operator.

    January's catalogue
    …
    Today's catalogue
    …

    FareCatalogue today = FareCatalogue.builder()
        .operator("Company1", new Tariff("c1-2026-01", Instant.EPOCH, JANUARY))
        .operator("Company1", new Tariff("c1-2026-02", FEB_1, FEBRUARY))
        .operator("Harbour",  new Tariff("hb-2026-01", Instant.EPOCH, HARBOUR,
                                         IncompleteTripPolicy.flat("5.00")))
        .build();
    
    new TripPricer(today).price(taps);   // the pricer never changes
    The same shape as FareCatalogueTest. Adding an operator or a fare rise is data.
    4.0 Charge

    Late taps fix the bill, not break it.

    Readers go offline, so taps turn up late, twice or out of order. Each one re-prices the card's whole day and only the difference is posted.

    Prices come from the real pricer. The ledger around it is my Part 2 design, simulated here.

    A contactless card validator on a pole at a tram stop

    Scroll to let the taps arrive

    Taps for card ··5559 on 22 Jan, in any order

    Closing is the operator's maximum journey time running out. Until then a tap on is open and nothing is charged.

    Try it: deliver #1, close, then deliver #2.

    The day, priced now

      Ledger

      posted $0.00
      Idempotency keyDeltaBecause
      Nothing posted yet.

      Inside a city bus at night: blue handrails and a card reader by the door
      5.0 Scale

      2,000 buses, one pure function.

      About 800k taps a day, around 100 a second at peak. Throughput is easy. Getting the charge right when taps arrive late, twice or out of order is the hard part.

      1 / 8

      Tap

      The reader admits the passenger offline: a genuine card, not on the deny list. Taps queue on the bus and upload when there's signal.

      Scroll to follow a tap
      Read the design note
      Taps flow from the reader through ingest, a stream and the trip engine to a ledger and payments. Declines return to the reader's deny list.card data zone (PCI DSS)Readeron the bus, offlineIngestIoT Core (MQTT)TapsDynamoDBStreamKinesis, by cardTrip engineTripPricerToken vaultKMS · CloudHSMTimersEventBridgeFare cataloguetariffs per operatorDeny listIoT jobsAcquirergatewayPaymentsone call per deltaOutboxwith the ledger writeLedgerdeltas, versioned

      Service icons: AWS Architecture Icons.

      6.0 Proof

      80 of 80 tests pass.

      Run when this page was built, against the same source the engine above was compiled from. 13 files, 714 lines, no dependencies.

      • Java 21
      • Gradle
      • JUnit 5

      Built 2026-12-06 16:28 UTC · ./gradlew test

      Backward compatibility2/2
      • Adding a new tariff never changes how older trips are priced
      • The original single-table constructor still behaves exactly as before
      Catalogue rules4/4
      • Rejects AReused tariff ID
      • Rejects two tariffs starting at the same instant
      • Rejects an empty catalogue
      • Tariffs can be added in any order
      Fare changes3/3
      • A trip is priced with the tariff in force when it started
      • A trip across midnight of a fare change keeps the old fare
      • The maximum fare for an incomplete trip follows the new tariff
      Several operators5/5
      • An operator with no tariff yet is reported, not priced
      • A stop belonging to another operator is unknown
      • A tap before an operator's first tariff is reported, not priced
      • Each operator applies its own incomplete-trip rule
      • Each operator prices with its own stops and fares
      Fare table16/16
      • Rejects unknown stops
      • Maximum fare follows AFare change
      • Rejects an empty table
      • Rejects negative and sub cent amounts
      • Rejects the same pair defined twice in either direction
      • Knows its stops
      • An incomplete trip from stop1 costs 7.30
      • An incomplete trip from stop2 costs 5.50
      • An incomplete trip from stop3 costs 7.30
      • Stop1 <-> stop2 costs 3.25
      • Stop2 <-> stop1 costs 3.25
      • Stop2 <-> stop3 costs 5.50
      • Stop3 <-> stop2 costs 5.50
      • Stop1 <-> stop3 costs 7.30
      • Stop3 <-> stop1 costs 7.30
      • Rejects AFare from AStop to itself
      PAN4/4
      • Rejects values that are not card numbers
      • Never leaks the full PAN through to string
      • Keeps the full value for the trip output
      • Masks the PAN when printed
      Sample data3/3
      • All six taps give three trips and one unmatched tap off
      • The sample charges $10.55 in total
      • Taps 1 and 2 produce exactly the trip given in the exercise
      Taps that are not charged6/6
      • A tap off at an unknown stop does not leave the passenger paying the maximum fare
      • Two known stops with no fare between them are reported, and the pricer does not fail
      • Tap off without ATap on is reported not charged
      • No taps give no trips
      • A lone tap on at an unknown stop is reported, not charged
      • A tap on at an unknown stop is reported with its tap off, nothing is charged
      Cancelled trips1/1
      • Charges nothing when on and off are at the same stop
      Completed trips2/2
      • Charges the fare between the two stops
      • Charges the same fare in the other direction
      Taps arriving late, out of order or more than once29/29
      • No copy of a tap ID reused with different content is trusted, whatever the arrival order
      • Taps with the same timestamp are ordered by ID
      • An identical resent tap is ignored and reported
      • Repetition 1 of 25
      • Repetition 2 of 25
      • Repetition 3 of 25
      • Repetition 4 of 25
      • Repetition 5 of 25
      • Repetition 6 of 25
      • Repetition 7 of 25
      • Repetition 8 of 25
      • Repetition 9 of 25
      • Repetition 10 of 25
      • Repetition 11 of 25
      • Repetition 12 of 25
      • Repetition 13 of 25
      • Repetition 14 of 25
      • Repetition 15 of 25
      • Repetition 16 of 25
      • Repetition 17 of 25
      • Repetition 18 of 25
      • Repetition 19 of 25
      • Repetition 20 of 25
      • Repetition 21 of 25
      • Repetition 22 of 25
      • Repetition 23 of 25
      • Repetition 24 of 25
      • Repetition 25 of 25
      • A late tap off turns an incomplete trip into a completed one when re-priced
      Incomplete trips4/4
      • Charges the highest fare from the stop when there is no tap off
      • A tap off on a different bus does not complete the trip
      • Leaves the missing fields empty in the output
      • A second tap on closes the first one as incomplete
      Several cards1/1
      • Interleaved taps from different cards are never paired together
      package dev.benzarti.fares;
      
      import java.math.BigDecimal;
      import java.util.ArrayList;
      import java.util.Comparator;
      import java.util.LinkedHashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.Objects;
      import java.util.Optional;
      import java.util.stream.Collectors;
      
      /**
       * Turns a list of taps into priced trips.
       *
       * <p>The pricer is a pure function of its input: the same taps always give the same trips, whatever
       * order they arrive in and however many times a tap is repeated. That is what lets a real system
       * simply re-run it when a late tap arrives (see {@code docs/DESIGN.md}).
       *
       * <p>Steps:
       * <ol>
       *   <li>Keep one copy of a tap resent with identical content; reject every copy of a tap ID that
       *       was reused with different content.</li>
       *   <li>Group the remaining taps by card and sort each card's taps by time, then by ID.</li>
       *   <li>Walk each card's taps, pairing every tap on with the next tap if it is a tap off on the
       *       same bus. Anything else closes the tap on as an incomplete trip.</li>
       *   <li>Price each trip with the tariff of its tap-on operator in force at its tap-on time. Report,
       *       rather than price, any trip that tariff cannot price: an unknown stop, or two stops with no
       *       fare between them.</li>
       * </ol>
       */
      public final class TripPricer {
      
          private static final Comparator<Tap> CHRONOLOGICAL =
                  Comparator.comparing(Tap::timestamp).thenComparingLong(Tap::id);
      
          private static final Comparator<Trip> OUTPUT_ORDER = Comparator
                  .comparing(Trip::started)
                  .thenComparing(trip -> trip.pan().value())
                  .thenComparingLong(Trip::tapOnId);
      
          /** Total order over anomalies, so two copies of a conflicting tap always come out the same way. */
          private static final Comparator<Anomaly> ANOMALY_ORDER = Comparator
                  .comparing((Anomaly a) -> a.tap().timestamp())
                  .thenComparingLong(a -> a.tap().id())
                  .thenComparing(a -> a.reason())
                  .thenComparing(a -> a.tap().type())
                  .thenComparing(a -> a.tap().stopId())
                  .thenComparing(a -> a.tap().companyId())
                  .thenComparing(a -> a.tap().busId())
                  .thenComparing(a -> a.tap().pan().value());
      
          private final FareCatalogue catalogue;
      
          /** Prices with one fare table for every operator and all time, as in the exercise. */
          public TripPricer(FareTable fares) {
              this(FareCatalogue.single(Objects.requireNonNull(fares, "fares")));
          }
      
          /** Prices with per-operator, versioned tariffs. */
          public TripPricer(FareCatalogue catalogue) {
              this.catalogue = Objects.requireNonNull(catalogue, "catalogue");
          }
      
          public PricingResult price(List<Tap> taps) {
              Objects.requireNonNull(taps, "taps");
              List<Anomaly> anomalies = new ArrayList<>();
      
              List<Tap> unique = deduplicate(taps, anomalies);
      
              Map<String, List<Tap>> byCard = unique.stream()
                      .collect(Collectors.groupingBy(tap -> tap.pan().value(), LinkedHashMap::new, Collectors.toList()));
      
              List<Trip> trips = new ArrayList<>();
              for (List<Tap> cardTaps : byCard.values()) {
                  cardTaps.sort(CHRONOLOGICAL);
                  buildTrips(cardTaps, trips, anomalies);
              }
      
              trips.sort(OUTPUT_ORDER);
              anomalies.sort(ANOMALY_ORDER);
              return new PricingResult(trips, anomalies);
          }
      
          /**
           * Readers on patchy connections resend taps, so the same tap can arrive more than once. Copies of
           * a tap ID that are all identical are a harmless resend: one is kept. If any copy differs, the ID
           * is a data integrity problem and <em>no</em> copy is trusted. Keeping "the first one received"
           * instead would make the result depend on arrival order.
           */
          private static List<Tap> deduplicate(List<Tap> taps, List<Anomaly> anomalies) {
              Map<Long, List<Tap>> byId = new LinkedHashMap<>();
              for (Tap tap : taps) {
                  Objects.requireNonNull(tap, "taps must not contain null");
                  byId.computeIfAbsent(tap.id(), id -> new ArrayList<>()).add(tap);
              }
              List<Tap> unique = new ArrayList<>();
              for (List<Tap> copies : byId.values()) {
                  Tap first = copies.getFirst();
                  boolean allIdentical = copies.stream().allMatch(first::equals);
                  if (allIdentical) {
                      unique.add(first);
                      copies.stream().skip(1).forEach(copy -> anomalies.add(new Anomaly(copy, Anomaly.Reason.DUPLICATE_TAP)));
                  } else {
                      copies.forEach(copy -> anomalies.add(new Anomaly(copy, Anomaly.Reason.CONFLICTING_TAP_ID)));
                  }
              }
              return unique;
          }
      
          private void buildTrips(List<Tap> cardTaps, List<Trip> trips, List<Anomaly> anomalies) {
              Tap openTapOn = null;
              for (Tap tap : cardTaps) {
                  if (tap.type() == TapType.ON) {
                      if (openTapOn != null) {
                          closeIncomplete(openTapOn, trips, anomalies);
                      }
                      openTapOn = tap;
                  } else if (openTapOn != null && openTapOn.sameVehicleAs(tap)) {
                      closeFinished(openTapOn, tap, trips, anomalies);
                      openTapOn = null;
                  } else {
                      if (openTapOn != null) {
                          closeIncomplete(openTapOn, trips, anomalies);
                          openTapOn = null;
                      }
                      anomalies.add(new Anomaly(tap, Anomaly.Reason.TAP_OFF_WITHOUT_TAP_ON));
                  }
              }
              if (openTapOn != null) {
                  closeIncomplete(openTapOn, trips, anomalies);
              }
          }
      
          /**
           * A trip its tariff cannot price is never guessed at, because for a tap on the guess would be the
           * maximum fare. That covers a stop the tariff does not know, and two known stops with no fare
           * between them. Both taps are reported and nothing is charged.
           */
          private void closeFinished(Tap on, Tap off, List<Trip> trips, List<Anomaly> anomalies) {
              Tariff tariff = tariffFor(on).orElse(null);
              if (tariff == null) {
                  anomalies.add(new Anomaly(on, Anomaly.Reason.NO_TARIFF));
                  anomalies.add(new Anomaly(off, Anomaly.Reason.NO_TARIFF));
                  return;
              }
              boolean onKnown = tariff.fares().knowsStop(on.stopId());
              boolean offKnown = tariff.fares().knowsStop(off.stopId());
              if (!onKnown || !offKnown) {
                  anomalies.add(new Anomaly(on, onKnown ? Anomaly.Reason.PAIRED_WITH_UNKNOWN_STOP : Anomaly.Reason.UNKNOWN_STOP));
                  anomalies.add(new Anomaly(off, offKnown ? Anomaly.Reason.PAIRED_WITH_UNKNOWN_STOP : Anomaly.Reason.UNKNOWN_STOP));
                  return;
              }
              if (on.stopId().equals(off.stopId())) {
                  trips.add(finished(on, off, tariff, TripStatus.CANCELLED, Money.ZERO));
                  return;
              }
              Optional<BigDecimal> fare = tariff.fares().findFare(on.stopId(), off.stopId());
              if (fare.isEmpty()) {
                  anomalies.add(new Anomaly(on, Anomaly.Reason.NO_FARE_BETWEEN_STOPS));
                  anomalies.add(new Anomaly(off, Anomaly.Reason.NO_FARE_BETWEEN_STOPS));
                  return;
              }
              trips.add(finished(on, off, tariff, TripStatus.COMPLETED, fare.get()));
          }
      
          private void closeIncomplete(Tap on, List<Trip> trips, List<Anomaly> anomalies) {
              Tariff tariff = tariffFor(on).orElse(null);
              if (tariff == null) {
                  anomalies.add(new Anomaly(on, Anomaly.Reason.NO_TARIFF));
              } else if (!tariff.fares().knowsStop(on.stopId())) {
                  anomalies.add(new Anomaly(on, Anomaly.Reason.UNKNOWN_STOP));
              } else {
                  trips.add(incomplete(on, tariff));
              }
          }
      
          private Optional<Tariff> tariffFor(Tap on) {
              return catalogue.tariffFor(on.companyId(), on.timestamp());
          }
      
          private static Trip finished(Tap on, Tap off, Tariff tariff, TripStatus status, BigDecimal charge) {
              return new Trip(on.timestamp(), off.timestamp(), on.stopId(), off.stopId(), charge,
                      on.companyId(), on.busId(), on.pan(), status, on.id(), off.id(), tariff.id());
          }
      
          private static Trip incomplete(Tap on, Tariff tariff) {
              BigDecimal charge = tariff.incompleteTrip().charge(on.stopId(), tariff.fares());
              return new Trip(on.timestamp(), null, on.stopId(), null, charge,
                      on.companyId(), on.busId(), on.pan(), TripStatus.INCOMPLETE, on.id(), null, tariff.id());
          }
      }