This page looks best with JavaScript enabled

Business layer vs. direct database operations

 ·   ·  ☕ 3 min read

I have this annoying behaviour to force as many things as I can through the business layer. This can be a boon and bane at the same time.

What do I mean by business layer?

Let’s say I have an application running on AdonisJS. For every operation (CRUD) -

  • I try to go through controllers/services
  • Almost all of them through APIs when called from front-end
  • Almost all of the operations through Lucid with exceptions through Database statements
  • Use Tasks or equivalent for batches
Everyone does this, why is it a point of discussion?

Going through business layer is good. You can control what gets read or updated when routing through the server layers.

For me personally, the use of business layer has been a cult-like thing.

You see - I had a long history with off-the-shelf applications. These applications foster cult-like behaviour when it comes to database updates. There are far too many things that can break an application for no reason, and the trust on some of the sensitive data (e.g. audit trails) can go for a toss when data updates are not handled responsibly.

Pros / cons

Using business layer enforces good behaviour -

  • Follow consistent business rules
  • Maintain data sanctity
  • Easier to change and maintain (well, this is subjective)
  • Easier to do a knowledge transfer to others in the team. Everyone is standardized on business layer :)

In smaller applications that I have been developing outside of my main line of work - this can mean -

  • Large scale updates / operations can be a pain - going through layers not optimized for the job can cause memory leaks that had never been found, severe performance issues
  • Batched operations are not always first-class citizens of an app (e.g. update hundred records in a batch to minimize database operations)
  • Complexity to the code-base when your back-end updates have to (ahem) skip a few rules

In general: wrong tool for the job = conflicts with the larger world and self.

What to do when I am in such a pickle?
  • Prefer business layer for ‘normal’ operations. Scale the layer for dozens of operations in one go. Implement batch handling but do not go over-board (subjective and overboard definition varies as per your requirements)
  • Don’t over-engineer your business layer to handle batch operations
  • Rely back on database operations or third party tools (e.g. an ETL)
  • Establish checks and balances for frequent third party operations (e.g. apply rules & validate file before the actual update to the database, create automated tasks to review critical data flowing in from external applications)
I still do not understand the problem

Good for you. Get back to work.

Stay in touch!
Share on

Prashanth Krishnamurthy
Prashanth Krishnamurthy
Technologist | Creator of Things