0
0
LLDsystem_design~7 mins

Transaction history in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When users perform multiple operations like payments or transfers, losing the record of these actions causes confusion and disputes. Without a reliable transaction history, users cannot verify past activities or detect errors, leading to trust issues and operational failures.
Solution
Maintain an ordered log of all transactions with details such as timestamp, amount, and status. This log acts as a single source of truth for all past operations, allowing users and systems to review, audit, and reconcile activities accurately.
Architecture
User App
Transaction
Audit & Reporting
Audit & Reporting

This diagram shows a user app sending transaction requests to a transaction service, which records them in a transaction history database. An audit service reads from this database for reporting and verification.

Trade-offs
✓ Pros
Provides a clear, immutable record of all user transactions for auditing and dispute resolution.
Enables easy rollback or reconciliation by referencing past transaction states.
Improves user trust by allowing transparent access to their transaction history.
✗ Cons
Storing detailed history increases storage requirements over time.
Maintaining consistency and ordering can add complexity in distributed systems.
Querying large histories may require indexing or archiving strategies to maintain performance.
Use when the system handles financial or critical user operations requiring audit trails, especially when transaction volume exceeds hundreds per second and regulatory compliance is needed.
Avoid if the system only performs simple, stateless operations with no need for historical audit or if transaction volume is extremely low (under 10 per minute) where overhead outweighs benefits.
Real World Examples
Stripe
Keeps detailed transaction histories for all payment operations to enable dispute resolution and compliance with financial regulations.
Amazon
Maintains order and payment transaction logs to track purchases, refunds, and account activities for customer service and auditing.
PayPal
Records every money transfer and payment event to provide users with a complete transaction history and fraud detection.
Code Example
The before code processes payments without saving any record. The after code adds a TransactionHistory class that stores each payment with details and timestamp. The PaymentProcessor uses this to save every transaction, enabling retrieval of user transaction history.
LLD
### Before: No transaction history tracking
class PaymentProcessor:
    def process_payment(self, user_id, amount):
        # Process payment logic
        print(f"Processed payment of {amount} for user {user_id}")


### After: With transaction history tracking
from datetime import datetime

class TransactionHistory:
    def __init__(self):
        self.records = []

    def add_record(self, user_id, amount, status):
        record = {
            'user_id': user_id,
            'amount': amount,
            'status': status,
            'timestamp': datetime.utcnow().isoformat() + 'Z'
        }
        self.records.append(record)

    def get_history(self, user_id):
        return [r for r in self.records if r['user_id'] == user_id]

class PaymentProcessor:
    def __init__(self, history):
        self.history = history

    def process_payment(self, user_id, amount):
        # Process payment logic
        status = 'success'  # Assume success for example
        self.history.add_record(user_id, amount, status)
        print(f"Processed payment of {amount} for user {user_id}")

# Usage
history = TransactionHistory()
processor = PaymentProcessor(history)
processor.process_payment('user123', 100)
print(history.get_history('user123'))
OutputSuccess
Alternatives
Event Sourcing
Stores all changes as a sequence of events rather than just final transaction records, enabling full state reconstruction.
Use when: Choose when you need full auditability and the ability to rebuild system state from events.
Snapshotting
Periodically saves the current state to reduce the need to replay the entire transaction history.
Use when: Choose when transaction history grows large and replaying all events becomes inefficient.
Summary
Transaction history prevents loss of critical operation records and supports auditing and dispute resolution.
It works by recording every transaction with details and timestamps in a consistent log.
This pattern is essential for financial systems and any application requiring reliable operation tracking.