Summary
An API was designed to return a list of stock names based on a provided sector name. However, it failed to handle edge cases, such as invalid sector names or sectors with no associated stocks, leading to unexpected 500 Internal Server Errors.
Root Cause
- Lack of input validation: The API did not validate sector names, allowing invalid inputs to reach the database query layer.
- Missing error handling: No fallback mechanism was in place for sectors with no associated stocks, causing database queries to return null results and trigger exceptions.
Why This Happens in Real Systems
- Assumptions about data integrity: Developers often assume sector names are always valid or that every sector has associated stocks.
- Overlooking edge cases: Junior engineers may focus on happy paths and neglect scenarios like empty results or malformed inputs.
Real-World Impact
- Service downtime: The API became unavailable for specific sector queries, affecting downstream applications.
- User frustration: Clients received cryptic error messages instead of meaningful responses.
- Increased support tickets: Operations teams faced a surge in reports about API failures.
Example or Code (if necessary and relevant)
def get_stocks_by_sector(sector_name):
query = f"SELECT stock_name FROM stocks WHERE sector = '{sector_name}'"
result = execute_query(query)
return result # No error handling or input validation
How Senior Engineers Fix It
- Add input validation: Use a whitelist or regex to validate sector names before processing.
- Implement error handling: Return an empty list or a 404 Not Found response for sectors with no stocks.
- Use parameterized queries: Prevent SQL injection and ensure query safety.
- Add logging and monitoring: Track invalid inputs and unexpected errors for proactive debugging.
Why Juniors Miss It
- Focus on functionality: Juniors prioritize implementing core features over edge cases.
- Limited experience with failures: Less exposure to real-world issues leads to overlooking potential pitfalls.
- Lack of defensive programming: Insufficient emphasis on validation, error handling, and robustness.