Skip to main content

Posts

Showing posts with the label SQL

DDD Aggregates: Solving the N+1 Performance Trap in Large Hierarchies

  It is the quintessential DDD hangover. You spend weeks modeling your domain with experts. You identify a   Distributor   entity that holds a collection of   Orders , which in turn hold   LineItems . It feels semantically correct: an Order cannot exist without a Distributor. You write the code, the tests pass, and you deploy. Three months later, the system hangs whenever a Distributor with 5,000 historical orders tries to open their dashboard. You have fallen into the  Mega-Aggregate Trap . By strictly adhering to the rule that "Aggregates are consistency boundaries," you have inadvertently forced your ORM (Entity Framework Core or Hibernate) to hydrate an entire object graph just to change a user's email address. This post details the root cause of this performance collapse and provides a rigorous architectural pattern to decouple large hierarchies without sacrificing data integrity. The Root Cause: Consistency vs. Transactional Reality The performance is...

Golang Context Pitfalls: Handling Cancellation in SQL Transactions

  A sudden spike in   MaxOpenConnections   errors or a PostgreSQL database choking on "Idle in transaction" states is rarely a database tuning issue. In Go services, it is almost exclusively a resource leak caused by mishandling   context.Context   cancellation during SQL transactions. When a request is cancelled—via client disconnect or timeout—the Go runtime stops processing the handler. However, if the database transaction ( sql.Tx ) is not explicitly rolled back, the underlying TCP connection remains reserved and the database session stays active, holding locks on rows and tables until the database's own timeout (often hours) kicks in. This post analyzes why standard  if err != nil  handling fails in concurrent environments and provides a closure-based transaction wrapper to guarantee atomicity and connection cleanup. The Root Cause: Connection Pooling vs. Context Lifecycle To understand the leak, we must look at how  database/sql  manage...