Video in progress

This calculation always gives the same result in tests, but in prod it is sometimes off by one tiyin. Explain the cause and the policy you need for financial calculations.

double total = payments.parallelStream()
        .mapToDouble(Payment::amount)
        .sum();

In a parallel stream a double sum is rounded differently depending on the order of the chunks, because floating-point addition isn't associative. The number of chunks depends on the core count, which differs between the test machine and the prod pod. For money you need BigDecimal or integer tiyin and a deterministic order.

📖 Answer

(a + b) + c and a + (b + c) are not always equal in double: every addition involves rounding. On a sequential stream the order is always the same, and so is the result. In parallel the source is split by core count: a different tree on an 8-core laptop and on a pod with 2 vCPUs. The result differs too.

An interesting detail: DoubleStream.sum() uses Kahan summation to reduce the error, so the difference is small, but it isn't zero. With reduce(0, Double::sum) the difference is larger.

That single tiyin turns into a mismatch between two systems in an accounting reconciliation, auditor questions, and an incident like "why did the report show a different number when it ran twice".

The policy I usually set:

  1. Money is never in double/float. BigDecimal (with an explicit scale and RoundingMode) or a long in tiyin. That goes for the DB too: numeric(19, 2), not double precision.
  2. When rounding happens is written in the rule: on each line or only at the end. That is a business decision, not a technical one, and the two give different results.
  3. Financial aggregation is deterministic: BigDecimal::add is associative, so whether it runs sequentially or in parallel the result is the same. long addition too (barring overflow).
  4. Reconciliation tests: run the report on the same data sequentially and in parallel, at different ForkJoinPool parallelism levels, and compare the results.
BigDecimal total = payments.stream()
        .map(Payment::amount)                 // BigDecimal
        .reduce(BigDecimal.ZERO, BigDecimal::add)
        .setScale(2, RoundingMode.HALF_EVEN);

In scientific computing (statistics, ML) a small difference is usually accepted: speed matters more there. But that too should be written down as an explicit decision, otherwise someone adds a snapshot test and it starts failing randomly in CI.