Bird
Raised Fist0
LLDsystem_design~7 mins

Fine calculation in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When fines are calculated without a clear, consistent method, errors occur leading to unfair penalties or revenue loss. Manual or ad-hoc fine calculations cause confusion and disputes among users and administrators.
Solution
A fine calculation system applies predefined rules to compute penalties automatically based on input parameters like delay duration or violation type. This ensures consistent, transparent, and error-free fine amounts every time.
Architecture
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│   User Input  │─────▶│ Fine Calculation│─────▶│ Fine Output   │
│ (violation,  │      │   Module       │      │ (amount,     │
│  delay, etc) │      │ (rules engine) │      │  details)    │
└───────────────┘      └───────────────┘      └───────────────┘

This diagram shows the flow from user input through the fine calculation module applying rules, producing the fine output.

Trade-offs
✓ Pros
Ensures consistent and repeatable fine calculations.
Reduces manual errors and disputes over fines.
Easily update rules without changing core logic.
Improves transparency and auditability of fines.
✗ Cons
Requires upfront design of fine rules and edge cases.
May need frequent updates if regulations change often.
Complex rules can increase system complexity and testing effort.
Use when fines must be calculated automatically for many users or transactions, especially if rules are complex or frequently updated.
Avoid if fines are rare, simple, or manually handled with low volume, where automation overhead outweighs benefits.
Real World Examples
Uber
Automates penalty fees for late cancellations or no-shows to ensure consistent charges across millions of rides.
Amazon
Calculates fines for sellers violating marketplace policies, applying different rules per violation type.
Airbnb
Applies fines for guest damages or late check-outs based on predefined rules to protect hosts fairly.
Code Example
The before code uses simple if-else logic directly, which is hard to extend or maintain. The after code encapsulates fine rules in a class with a list of condition-action pairs, making it easy to add or modify rules without changing the calculation method.
LLD
### Before: naive fine calculation without clear structure

def calculate_fine(days_late):
    if days_late <= 0:
        return 0
    elif days_late <= 5:
        return days_late * 10
    else:
        return 100


### After: structured fine calculation using a class and rules

class FineCalculator:
    def __init__(self):
        self.rules = [
            (lambda days: days <= 0, lambda days: 0),
            (lambda days: days <= 5, lambda days: days * 10),
            (lambda days: True, lambda days: 100)
        ]

    def calculate(self, days_late):
        for condition, action in self.rules:
            if condition(days_late):
                return action(days_late)


# Usage
calculator = FineCalculator()
fine = calculator.calculate(3)  # returns 30
OutputSuccess
Alternatives
Manual fine calculation
Fines are computed by humans case-by-case without automation.
Use when: Use only when volume is very low and rules are simple or frequently changing.
Rule engine integration
Uses a dedicated external rule engine to manage and execute fine calculation rules.
Use when: Choose when fine rules are very complex and need non-developer management.
Summary
Automated fine calculation prevents errors and disputes by applying consistent rules.
Designing fine calculation as a flexible, rule-based system improves maintainability.
Automation is essential when fines are frequent, complex, or impact many users.

Practice

(1/5)
1.

What is the primary purpose of a fine calculation system in low-level design?

easy
A. To automatically compute charges for rule violations
B. To store user personal information securely
C. To manage user login and authentication
D. To generate reports on system performance

Solution

  1. Step 1: Understand the system goal

    The fine calculation system is designed to handle rule violations and compute the corresponding charges automatically.
  2. Step 2: Identify the main function

    Its main function is to calculate fines based on violation details and fixed rates.
  3. Final Answer:

    To automatically compute charges for rule violations -> Option A
  4. Quick Check:

    Fine calculation = automatic charge computation [OK]
Hint: Focus on the system's main task: charging fines [OK]
Common Mistakes:
  • Confusing fine calculation with user management
  • Thinking it handles authentication
  • Assuming it generates performance reports
2.

Which of the following is the correct way to represent a fine rate for a violation type in a configuration file?

violation_fine_rates = {
    'speeding': 100,
    'parking': 50,
    'signal_jump': 150
}
easy
A. Using a boolean flag for each violation
B. Using a list of fine amounts only
C. Using a dictionary with violation types as keys and fine amounts as values
D. Using a string with violation names separated by commas

Solution

  1. Step 1: Analyze the data structure

    The example shows a dictionary mapping violation names to their fine amounts, which is clear and easy to update.
  2. Step 2: Compare with other options

    Lists or strings do not map violation types to amounts directly, and booleans cannot store fine values.
  3. Final Answer:

    Using a dictionary with violation types as keys and fine amounts as values -> Option C
  4. Quick Check:

    Dictionary maps violation to fine [OK]
Hint: Use key-value pairs for clear violation-to-fine mapping [OK]
Common Mistakes:
  • Using lists without keys loses violation context
  • Using strings cannot store amounts
  • Booleans cannot represent fine values
3.

Given the following code snippet, what will be the total fine calculated?

violation_fine_rates = {'speeding': 100, 'parking': 50}
violations = ['speeding', 'parking', 'speeding']
total_fine = sum(violation_fine_rates[v] for v in violations)
print(total_fine)
medium
A. 150
B. 200
C. 300
D. 250

Solution

  1. Step 1: Calculate fine for each violation

    Violations are 'speeding', 'parking', 'speeding'. Their fines are 100, 50, and 100 respectively.
  2. Step 2: Sum all fines

    Total fine = 100 + 50 + 100 = 250.
  3. Final Answer:

    250 -> Option D
  4. Quick Check:

    100 + 50 + 100 = 250 [OK]
Hint: Add fines for each violation in the list [OK]
Common Mistakes:
  • Counting each violation only once
  • Adding fines incorrectly
  • Ignoring repeated violations
4.

Identify the error in the following fine calculation code snippet:

violation_fine_rates = {'speeding': 100, 'parking': 50}
violations = ['speeding', 'parking', 'signal_jump']
total_fine = sum(violation_fine_rates[v] for v in violations)
print(total_fine)
medium
A. SyntaxError due to missing colon
B. KeyError occurs because 'signal_jump' is not in the rates dictionary
C. TypeError because sum cannot add strings
D. No error, code runs fine

Solution

  1. Step 1: Check dictionary keys against violations

    'signal_jump' is not a key in violation_fine_rates, so accessing it causes a KeyError.
  2. Step 2: Understand error type

    Attempting to access a missing key in a dictionary raises KeyError in Python.
  3. Final Answer:

    KeyError occurs because 'signal_jump' is not in the rates dictionary -> Option B
  4. Quick Check:

    Missing key access = KeyError [OK]
Hint: Check if all violation keys exist in the rates dictionary [OK]
Common Mistakes:
  • Assuming missing keys return zero
  • Confusing KeyError with SyntaxError
  • Ignoring runtime errors
5.

You are designing a fine calculation system that must support multiple violation types, each with different fine rates and possible discounts for repeat offenses. Which design approach is best?

hard
A. Use a dictionary mapping violation types to base fines and add logic to apply discounts based on offense count
B. Store all fines as a single fixed value and ignore violation types
C. Calculate fines manually each time without storing rates
D. Use a list of fines without linking to violation types

Solution

  1. Step 1: Identify need for flexible fine rates

    Different violation types require different base fines, so a mapping structure is needed.
  2. Step 2: Incorporate discount logic

    Discounts for repeat offenses require additional logic applied on top of base fines.
  3. Step 3: Choose design approach

    A dictionary for base fines plus discount logic is clear, scalable, and easy to update.
  4. Final Answer:

    Use a dictionary mapping violation types to base fines and add logic to apply discounts based on offense count -> Option A
  5. Quick Check:

    Dictionary + discount logic = scalable design [OK]
Hint: Map base fines and add discount logic for repeats [OK]
Common Mistakes:
  • Ignoring violation types in fine calculation
  • Hardcoding fines without flexibility
  • Not handling repeat offense discounts