How UberPool helped me understand EFCore's DbContextPooling 🤫.

After a very hectic week, I decided to watch movies through out the weekend. Having missed out a lot on my favorite TV shows and latest movies, I had compiled a list of movies to binge-watch and STUBER, was on the list. Halfway through the movie, Dave Bautista - a cop with terrible vision - ordered a ride and accidentally selected the UberPool option.

Uberpool is the new ride option (probably just to me) that matches you with riders heading in the same direction, so you can share the ride and cost.

Although DbContext Pooling has been around since EFCore 2.0 was released, I hadn't tried using it, owing mostly to the fact that ASP.Net Core 2.2 starter template with authentication already registers my DbContext in the IoC container (for dependency injection 😜). Hearing about UberPool reminded me of DbContextPooling and I decided to finally try it out only to find out that UberPool and DbContextPooling are quite similar, and here's why :

  • Just like UberPool matches you with people who are already on a route instead of ordering a entirely new ride, context pooling tries to find an instance of the dbcontext in memory and if it cant find one, it creates a new instance. Without context pooling enabled,as soon as a requested instance of a dbcontext has been provided by dependency injection, and that instance is no longer in use, it is disposed. Context pooling allows you to "share" exisiting instances of the dbcontext since no-longer-in-use instances return to a pool.

  • UberPool aims to save you money, context pooling can also indirectly save you money by increasing the performance of your application. To demonstrate this, I have a simple ASP.Net Core application to show a list of Uber drivers.

Scenario One - Context Pooling disabled Screenshot (3).png

Using the Stopwatch class from the System.Diagnostics namespace, I was able to record how long it took to create an instance of the dbcontext, to add an uber driver to the database and get all uber driver records from the database.

Screenshot (6).png Screenshot (5).png

And here are the results:

Screenshot (8).png

It took averagely 0.7 seconds to perform create operation for three trials and 0.3 seconds to get all records(3 drivers) from the database.

Screenshot (7).png

Scenario Two - Context Pooling enabled

Screenshot (13).png

It took an average of 0.02 seconds to create an uber driver and about 0.01 to get all uber driver records from the database.

Screenshot (11).png

Screenshot (12).png

STUBER is a lovely movie. The driver for the ride ended up dating Bautista's daughter 🤣. You should see it sometime.