Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Reader activity
0 Useful 2 Views 10 min Read — No ratings
Backend Development
10 min read

Why Partial Refunds Overpay by 1 Cent: Fixing Discount Allocation in Java E-commerce Systems

This article explains how naive discount splitting causes rounding errors that make partial refunds exceed the original payment, and demonstrates a robust solution using the largest remainder method, per-unit order amount snapshots, and idempotent refund reservation to ensure financial consistency in Java e-commerce systems.

Problem: Discount Allocation Rounding Errors Cause Over-Refunds

In a mall system, a user buys three items at 33.33 each, uses a 10 discount coupon, and pays 89.99. If the 10 discount is evenly split (3.33 per item), each item's paid amount becomes 30.00. When the user refunds all three items separately, the system returns 90.00 — one cent more than the actual payment. Although the difference is tiny, financial systems require exact reconciliation. The issue worsens with multiple promotions (item discounts, shop coupons, platform coupons) and repeated partial refunds.

Why BigDecimal Alone Does Not Solve It

Many Java developers reach for BigDecimal for monetary precision. However, the problem is not floating-point precision but the remainder from dividing a discount among discrete cent units . For example:

BigDecimal discount = new BigDecimal("10.00");
BigDecimal average = discount.divide(
    BigDecimal.valueOf(3),
    2,
    RoundingMode.HALF_UP
);
System.out.println(average);          // 3.33
System.out.println(average.multiply(BigDecimal.valueOf(3))); // 9.99

The total allocated discount becomes 9.99 instead of 10.00 because 10/3 is a repeating decimal and the currency's smallest unit is one cent. The system must decide who gets the remaining cent.

Illustration of the error:

Item A: Original 33.33, Wrong Discount 3.33, Paid 30.00

Item B: Original 33.33, Wrong Discount 3.33, Paid 30.00

Item C: Original 33.33, Wrong Discount 3.33, Paid 30.00

Total: Original 99.99, Wrong Discount 9.99, Paid 90.00 BigDecimal fixes decimal arithmetic precision but does not enforce amount conservation — the business rule that the sum of allocated discounts must equal the original discount.

Correct Algorithm: Largest Remainder Method

When item prices differ, discounts should be allocated proportionally. The Largest Remainder Method works in four steps:

Calculate each item's theoretical discount by price proportion.

Round each down to the nearest cent (floor).

Compute the unallocated remainder (original discount minus sum of floored discounts).

Distribute the remaining cents one by one to items with the largest fractional remainders until exhausted.

Example: Order total 100.00, discount 10.00.

Item A: Price 29.99, Theoretical Discount 2.999, Final Discount 3.00, Paid 26.99

Item B: Price 39.99, Theoretical Discount 3.999, Final Discount 4.00, Paid 35.99

Item C: Price 30.02, Theoretical Discount 3.002, Final Discount 3.00, Paid 27.02

Total: Price 100.00, Theoretical Discount 10.000, Final Discount 10.00, Paid 90.00

This preserves the total discount exactly while minimizing per-item deviation. It is fairer than dumping all remainder onto the last item.

Largest remainder method illustration
Largest remainder method illustration

Java 21 Implementation: Generic Discount Allocator

Store all amounts as integer cents to avoid decimal drift and simplify integration with payment gateways. The allocator uses BigInteger for intermediate multiplication to prevent long overflow, divideAndRemainder to get quotient and remainder in one step, and sorts by remainder then item ID for deterministic results regardless of input order.

import java.math.BigInteger;
import java.util.*;

public class DiscountAllocator {
    public record Unit(long id, long price) {}
    public record Share(long id, long price, long discount) {
        public long paid() { return price - discount; }
    }
    private record Part(int index, BigInteger remainder) {}

    public static List<Share> allocate(List<Unit> units, long discount) {
        List<Unit> items = List.copyOf(units);
        long total = 0;
        Set<Long> ids = new HashSet<>();
        for (Unit unit : items) {
            if (unit.price() < 0 || !ids.add(unit.id())) {
                throw new IllegalArgumentException("Invalid item amount or duplicate id");
            }
            total = Math.addExact(total, unit.price());
        }
        if (discount < 0 || discount > total) {
            throw new IllegalArgumentException("Invalid discount amount");
        }
        if (total == 0) {
            return items.stream()
                .map(u -> new Share(u.id(), u.price(), 0))
                .toList();
        }
        BigInteger divisor = BigInteger.valueOf(total);
        long[] allocated = new long[items.size()];
        List<Part> parts = new ArrayList<>();
        long remaining = discount;
        // Phase 1: proportional floor allocation
        for (int i = 0; i < items.size(); i++) {
            Unit unit = items.get(i);
            BigInteger numerator = BigInteger.valueOf(discount)
                .multiply(BigInteger.valueOf(unit.price()));
            BigInteger[] result = numerator.divideAndRemainder(divisor);
            long base = result[0].longValueExact();
            allocated[i] = base;
            remaining -= base;
            parts.add(new Part(i, result[1]));
        }
        // Phase 2: sort by remainder descending, then by id for tie-break
        parts.sort(Comparator.comparing(Part::remainder).reversed()
            .thenComparingLong(p -> items.get(p.index()).id()));
        // Phase 3: compensate remaining cents
        for (int i = 0; i < remaining; i++) {
            int idx = parts.get(i).index();
            allocated[idx]++;
        }
        // Phase 4: build result
        List<Share> shares = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            Unit unit = items.get(i);
            shares.add(new Share(unit.id(), unit.price(), allocated[i]));
        }
        return List.copyOf(shares);
    }
}

Test with three items of 3333 cents each and a 1000-cent discount:

var units = List.of(
    new DiscountAllocator.Unit(1, 3333),
    new DiscountAllocator.Unit(2, 3333),
    new DiscountAllocator.Unit(3, 3333)
);
var shares = DiscountAllocator.allocate(units, 1000);
for (var s : shares) {
    System.out.printf("Item:%d Price:%d Discount:%d Paid:%d%n",
        s.id(), s.price(), s.discount(), s.paid());
}
long totalPaid = shares.stream().mapToLong(DiscountAllocator.Share::paid).sum();
System.out.println("Total paid: " + totalPaid);

Output:

Item:1 Price:3333 Discount:334 Paid:2999
Item:2 Price:3333 Discount:333 Paid:3000
Item:3 Price:3333 Discount:333 Paid:3000
Total paid: 8999

Now any sequence of partial refunds sums exactly to 89.99.

Handling Multiple Quantities: Per-Unit Amount Snapshots

If a user buys 10 units of the same SKU and refunds in batches (3, then 2, then 5), recalculating discounts each time reintroduces rounding errors. The fix: at order creation, split the allocated discount down to the minimum refundable unit (each individual item) and persist a snapshot.

CREATE TABLE order_item_unit (
    id BIGINT PRIMARY KEY,
    order_id BIGINT NOT NULL,
    order_item_id BIGINT NOT NULL,
    unit_no INT NOT NULL,
    original_amount BIGINT NOT NULL,
    discount_amount BIGINT NOT NULL,
    paid_amount BIGINT NOT NULL,
    refund_status VARCHAR(20) NOT NULL DEFAULT 'AVAILABLE',
    refund_no VARCHAR(64),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE(order_item_id, unit_no),
    CHECK (original_amount >= 0),
    CHECK (discount_amount >= 0),
    CHECK (paid_amount >= 0),
    CHECK (original_amount = discount_amount + paid_amount),
    CHECK (refund_status IN ('AVAILABLE','REFUNDING','REFUNDED'))
);
CREATE INDEX idx_item_unit_refund ON order_item_unit (order_item_id, refund_status, unit_no);

This table stores the transaction-time financial snapshot , immune to later price changes, coupon expirations, or promotion rule modifications. For high-volume wholesale, group by discount amount and quantity range instead of creating a row per unit.

Partial Refund Service: Idempotent Reservation with Row Locking

When a refund request arrives, the service must:

Create an idempotent refund request record (using ON CONFLICT DO NOTHING on refund_no).

Lock the required number of AVAILABLE units with SELECT ... FOR UPDATE.

Sum their paid_amount — no recalculation.

Mark those units REFUNDING and link the refund_no.

Update the refund request with the calculated amount and status PROCESSING.

@Service
@RequiredArgsConstructor
public class RefundService {
    private final JdbcTemplate jdbcTemplate;
    public record RefundUnit(long id, long paidAmount) {}

    @Transactional
    public long reserveRefund(String refundNo, long orderId, long itemId, int quantity) {
        if (quantity <= 0) throw new IllegalArgumentException("Invalid quantity");
        int inserted = jdbcTemplate.update("""
            INSERT INTO refund_request (refund_no, order_id, order_item_id, quantity, status)
            VALUES (?, ?, ?, ?, 'PENDING')
            ON CONFLICT (refund_no) DO NOTHING
            """, refundNo, orderId, itemId, quantity);
        if (inserted == 0) {
            return jdbcTemplate.queryForObject("""
                SELECT refund_amount FROM refund_request
                WHERE refund_no = ? AND order_id = ? AND order_item_id = ? AND quantity = ?
                """, Long.class, refundNo, orderId, itemId, quantity);
        }
        List<RefundUnit> units = jdbcTemplate.query("""
            SELECT id, paid_amount FROM order_item_unit
            WHERE order_id = ? AND order_item_id = ? AND refund_status = 'AVAILABLE'
            ORDER BY unit_no LIMIT ? FOR UPDATE
            """, (rs, rn) -> new RefundUnit(rs.getLong("id"), rs.getLong("paid_amount")),
            orderId, itemId, quantity);
        if (units.size() != quantity) throw new IllegalStateException("Insufficient refundable units");
        long refundAmount = 0;
        for (RefundUnit u : units) {
            refundAmount = Math.addExact(refundAmount, u.paidAmount());
            int updated = jdbcTemplate.update("""
                UPDATE order_item_unit SET refund_status = 'REFUNDING', refund_no = ?
                WHERE id = ? AND refund_status = 'AVAILABLE'
                """, refundNo, u.id());
            if (updated != 1) throw new IllegalStateException("Refund status changed");
        }
        jdbcTemplate.update("""
            UPDATE refund_request SET refund_amount = ?, status = 'PROCESSING'
            WHERE refund_no = ?
            """, refundAmount, refundNo);
        return refundAmount;
    }
}

This avoids remote payment calls inside the DB transaction, prevents double-refunding the same unit under concurrent requests, and supports idempotent retries. Production code should also verify order ownership, payment status, and after-sales rules before entering this method. After the payment gateway confirms success, update both tables to REFUNDED; on definite failure, release the reservation; on unknown status, keep REFUNDING and poll.

Refund reservation flow
Refund reservation flow

Multiple Promotion Types: Layered Allocation with Detail Records

Real platforms combine shop full-reduction, shop coupons, and platform coupons. Each may apply to different item subsets and have different funding parties. Merging all discounts into one pool loses traceability. Instead, apply promotions in a predefined priority order, each layer allocating only among eligible items, and record every allocation separately.

CREATE TABLE order_discount_detail (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id BIGINT NOT NULL,
    order_item_unit_id BIGINT NOT NULL,
    promotion_id VARCHAR(64) NOT NULL,
    promotion_type VARCHAR(32) NOT NULL,
    discount_amount BIGINT NOT NULL,
    funding_party VARCHAR(32) NOT NULL,
    calculation_order INT NOT NULL,
    CHECK (discount_amount >= 0),
    UNIQUE (order_item_unit_id, calculation_order)
);

This enables:

Exact reconstruction of each item's paid amount.

Merchant settlement and platform subsidy accounting.

Coupon return logic upon refund (which promotion gave how much).

Financial auditing from the immutable snapshot.

Promotion layering diagram
Promotion layering diagram

Note: If business rules allow re-evaluating promotions after partial returns (e.g., voiding a full-reduction threshold), additional clawback logic and upfront user disclosure are required. The presented design freezes the deal at payment time.

Verification: Constraints Over Happy-Path Tests

The allocator must satisfy invariants for all inputs, not just a few cases. A verification routine checks:

public static void verify(List<Unit> units, long discount) {
    var shares = DiscountAllocator.allocate(units, discount);
    long originalTotal = units.stream().mapToLong(Unit::price).sum();
    long discountTotal = shares.stream().mapToLong(Share::discount).sum();
    long paidTotal = shares.stream().mapToLong(Share::paid).sum();
    if (discountTotal != discount) throw new AssertionError("Discount not conserved");
    if (paidTotal != originalTotal - discount) throw new AssertionError("Paid amount not conserved");
    for (var s : shares) {
        if (s.paid() < 0 || s.discount() < 0 || s.discount() > s.price())
            throw new AssertionError("Illegal per-item allocation");
    }
}

Essential test scenarios:

10 discount split across 3 items → Total discount exactly 10

1 cent discount across 100 items → Only 1 cent allocated

Item price zero → No discount allocated

Discount equals total price → Paid amount zero

Items with different prices → Proportional allocation

Shuffle input order → Per-item allocation unchanged

Multiple partial refunds → Sum of refunds equals original paid

Duplicate refund requests → No double reservation

Concurrent refund requests → No unit refunded twice

Payment gateway result unknown → Retain processing state

Promotion rules change after payment → Original snapshot unaffected

Time complexity is O(n log n) (remainder sort), space O(n). No Redis or distributed framework needed for typical order sizes.

Conclusion

Many mall systems only store item list price, quantity, total discount, and final paid amount. That works for payment but breaks during partial refunds, merchant settlement, platform subsidy reconciliation, and financial audits — all of which need the per-item transaction-time financial snapshot . BigDecimal solves calculation precision .

Largest Remainder Method solves discount conservation .

Order amount snapshots solve historical immutability .

Refund state machine solves double-spend prevention .

These are not microservice architecture problems; they are domain modeling problems. The key is deciding upfront how every cent is attributed at order creation so that refunds never require a system redesign over a single penny.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment