Performance problems due to impedance mismatch

When tuning the application for performance, it will be very easy to understand the problem if we think in terms of what is impeding the flow. In other words impedance mismatch will be a big problem like how it causes in electrical circuits.

The first thing to keep in mind while working with an ORM framework is the impedance mismatch. The framework helps you hide the complexities of querying a RDBMS but it also hides the understanding of how things work when translated from object to rows in multiple tables thereby leaking abstraction.

Which is the most common problem when using an ORM?

N+1 — This has been there ever since ORM frameworks came in but newer programmers always have to go through this ritual of learning to deal with this problem. The problem of firing as many queries as there as many objects to be retrieved from the collection is N+1. Objects deal with Lists, Maps and compose other objects as well. Relational model deals with other tables as ‘one to many’, ‘many-to-many’ and the ‘many-to-one’. Take an example, if the main object here is a TV, then the speakers and the display are sub objects contained in TV. Though the speakers will never be associated with any other TV, you will still be forced to represent them in a separate table with ‘one-to-many’ relationship from TV.

While you treat TV as an object that contains speaker and display, you are forced to store it across multiple tables. When you read from the db through ORM then you treat it as a single object retrieval but the ORM will fire more than a single query in default settings.

What is the resolution? We need to be conscious of the calls that are going to the db, sometimes we need to do lazy fetch and sometimes eager which has to be explicit. It should not be left with the default settings to operate on. Another option is to design the db such that the non queryable parts of data goes as JSON so the relational mismatch is avoided altogether. Postgres supports this as JSONB.

While there are some more concerns to be talked about bridging objects and relations, the single most often encountered bottleneck for new programmers is to think about how the queries are getting executed when using ORMs. Read more about Object-Relational impedance mismatch written by many programmers to understand about this a lot.

Trim tab