Designing Business Logic and Evolving Public APIs
BehavioralModel answerLast updated
Design extensible object-oriented backend logic and safely modify production APIs with versioning, compatibility, and rollout strategies.
You're working on a mature backend system that serves external clients. This problem has two parts:
Part 1: Implementing New Business Logic
Your team needs to add a feature to an existing service. Describe your approach to designing this using object-oriented principles. Address:
- How you identify which domain objects to create
- How you assign responsibilities across classes
- How you keep orchestration separate from core business rules
- How you ensure the design is testable and can accommodate future changes
Part 2: Modifying a Production API
You must change an endpoint that external clients already depend on. Outline the process you'd follow to ship this change without breaking existing integrations. Cover:
- Evaluating backward compatibility
- Choosing an appropriate versioning strategy
- Testing approach before deployment
- Rollout methodology
- Monitoring and observability
- Client communication plan
Use a concrete example to ground your answer. Explain your reasoning and the tradeoffs involved.
Hints
Hint 1
Start with a specific business scenario and use it throughout both parts to keep your answer concrete
Hint 2
Consider the difference between adding optional fields versus removing or changing existing behavior
Hint 3
Think about where business rules should live versus where coordination logic belongs
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Designing Business Logic and Evolving Public APIs
Framing with a Concrete Example
I'll use a payments service that needs to support refund processing as my example. The new rule: refunds up to 30 days from purchase are automatically approved; older requests need manual review. Later, we need to modify the POST /refunds endpoint to return additional status metadata.
Part 1: Object-Oriented Design for Business Logic
Identifying Domain Objects
I look for concepts that have both state and behavior, not just data containers.
Entities (have unique identity):
Transaction- represents a payment with an ID and lifecycleRefundRequest- tracks the refund attempt itself
Value Objects (immutable, compared by value):
Amount- wraps currency math to avoid floating-point errorsRefundStatus- approved, pending, rejectedTimestamp- for deterministic time handling in tests
Domain Services (behavior that doesn't belong to one entity):
RefundEligibilityChecker- encapsulates the approval rules
I ask clarifying questions: Does the 30-day window use transaction date or settlement date? What happens with partial refunds? These ambiguities become test scenarios.
Assigning Responsibilities
I follow "Tell, Don't Ask" - objects should make decisions about their own data.
Transactionknows if it's already been fully refunded (invariant enforcement)RefundEligibilityCheckerdetermines approval based on business rulesRefundRequestvalidates that requested amount doesn't exceed original transaction
Anti-pattern to avoid: putting if (daysSincePurchase < 30) logic in the controller or database layer. Business rules belong in the domain layer.
Separating Orchestration from Business Logic
I structure the code in distinct layers:
Domain Layer (pure business logic):
class Amount:
def __init__(self, value: Decimal, currency: str):
if value < 0:
raise ValueError("amount cannot be negative")
self.value = value
self.currency = currency
def is_valid_refund_for(self, original: 'Amount') -> bool:
return self.currency == original.currency and self.value <= original.value
class RefundEligibilityChecker:
def __init__(self, auto_approve_window_days: int):
self.window = auto_approve_window_days
def can_auto_approve(self, transaction_date: date, request_date: date) -> bool:
age_days = (request_date - transaction_date).days
return age_days <= self.window
class Transaction:
def __init__(self, txn_id: str, amount: Amount, date: date):
self.id = txn_id
self.amount = amount
self.date = date
self.total_refunded = Amount(Decimal("0"), amount.currency)
def remaining_refundable(self) -> Amount:
remaining = self.amount.value - self.total_refunded.value
return Amount(remaining, self.amount.currency)
Application Service (orchestration only):
class RefundService:
def __init__(self,
transaction_repo: TransactionRepository,
refund_repo: RefundRepository,
eligibility_checker: RefundEligibilityChecker,
clock: Clock):
self.transactions = transaction_repo
self.refunds = refund_repo
self.checker = eligibility_checker
self.clock = clock
def process_refund_request(self, txn_id: str, amount: Amount) -> RefundRequest:
# Load, delegate to domain, persist - no business logic here
txn = self.transactions.find_by_id(txn_id)
if not amount.is_valid_refund_for(txn.remaining_refundable()):
raise InvalidRefundError("amount exceeds refundable balance")
today = self.clock.today()
auto_approved = self.checker.can_auto_approve(txn.date, today)
refund = RefundRequest(
transaction=txn,
amount=amount,
status=RefundStatus.APPROVED if auto_approved else RefundStatus.PENDING
)
self.refunds.save(refund)
return refund
This separation means the domain layer has zero dependencies on databases, HTTP, or external services. It's pure logic that can run in milliseconds in unit tests.
Making It Testable and Extensible
Dependency Injection: The service receives all dependencies through its constructor, making tests straightforward.
Strategy Pattern for Rules: When we later add "VIP customers get 90-day auto-approval," we create a new VIPRefundEligibilityChecker class rather than adding conditionals.
Injected Clock: Tests pass in a fake clock so we can verify behavior at day 29, day 30, and day 31 deterministically.
Test Structure:
- Unit tests on
RefundEligibilityChecker: boundary cases (exactly 30 days, 29 days, 31 days) - Unit tests on
Transaction: exceeding refundable amount, currency mismatches - Service tests with in-memory fakes: complete workflows
- Integration tests: a handful against real database
Extensibility tradeoff: I don't build a rules engine for one rule. When a third variant appears, then extract a common abstraction (YAGNI principle).
Part 2: Safely Modifying a Production API
Step 1: Classify the Change
Our change adds processing_time_seconds and review_required fields to the response.
This is additive - we're not removing anything or changing semantics. Existing clients ignore unknown fields (tolerant reader pattern from Postel's Law).
If we were removing legacy_status_code or changing created_at from Unix timestamp to ISO8601, that would be breaking and require versioning.
Step 2: Backward Compatibility Strategy
For this additive change:
- Add new fields as optional in schema
- Maintain all existing fields unchanged
- Document that clients must ignore unrecognized fields
- Keep error response format identical
For a breaking change, I'd use expand-migrate-contract:
- Deploy v2 endpoint (
/v2/refunds) alongside v1 - Both versions share domain logic, with adapters translating to different response formats
- Migrate clients progressively
- Deprecate v1 with sunset date
- Remove v1 only after traffic drops below 1%
Versioning choice: Use URI versioning (/v1/, /v2/) if the team already does this, or Accept-Version header if that's the convention. Consistency with existing patterns matters more than theoretical purity.
Step 3: Testing Strategy
Schema validation:
- OpenAPI spec diff in CI - fails if breaking changes detected
- JSON Schema tests verify both old and new field formats
Contract tests:
- Snapshot tests ensure v1 responses stay byte-identical
- Consumer-driven contracts (Pact-style) for major clients
- Example: mobile app team provides fixture data and expected responses
Pre-production validation:
- Staging environment with production data snapshot
- Shadow mode: run new code alongside old, compare outputs without serving results
- Canary in sandbox environment where partners test integrations
Step 4: Rollout Process
Gradual deployment:
- Deploy to 1% of traffic (single availability zone)
- Monitor error rates, latency p99, and new field population rate
- If stable after 2 hours, expand to 10%
- Then 50%, then 100% over 24 hours
Feature flag: Wrap new fields in a flag so we can disable instantly if issues arise without redeploying.
Rollback plan: Previous version stays deployed; traffic shift takes 30 seconds via load balancer config.
Step 5: Monitoring and Observability
Metrics to track:
- Error rate for endpoint (should stay flat)
- Latency percentiles (p50, p95, p99)
- New field population rate (should be 100% within minutes)
- Client version distribution from User-Agent
Alerts:
- Error rate > 0.5% sustained for 5 minutes
- p99 latency increases by >20%
- New fields missing in responses
Logging:
- Structured logs with request ID for tracing
- Log when new code path executes
- Capture client version in metadata
Step 6: Client Communication
Timeline:
- T-14 days: Email API consumers with changelog and new field documentation
- T-7 days: Publish examples in developer docs, update sandbox
- T-1 day: Reminder with exact deployment time window
- T+0: Deploy during low-traffic window (3am in primary user timezone)
- T+1 day: Confirmation email with rollout completion
Documentation:
- Update OpenAPI spec
- Add code samples showing new fields
- Migration guide (even for additive changes, show best practices)
Support:
- Dedicated Slack channel for questions during rollout
- On-call engineer monitoring for first 48 hours
Key Tradeoffs
Design complexity vs. flexibility: Starting with a strategy pattern for one rule adds code but pays off when the second variant arrives. I'd begin simple and refactor when the pattern emerges.
Versioning overhead: Running two API versions doubles testing and maintenance burden. I'd only do this for truly breaking changes, not additive ones.
Rollout speed vs. safety: A 24-hour gradual rollout delays feature availability but catches issues before they affect all users. For critical fixes, I'd accept more risk and deploy faster with closer monitoring.
The core principle: treat public APIs as contracts with real consequences for breaking them. Internal refactoring is cheap; client migrations are expensive.