Database vs REST API – Which Is Faster?

databaserestsql

What is faster performance wise? Creating a REST API and having your web app use the REST API to do all interactions with your database OR querying your database directly (i.e. using whatever typical object your language uses to query a database such as JDBC for Java)?

The way I see it with REST:

  1. You make an object in your code to call the REST method
  2. Call http method
  3. Code inside your REST API queries the database
  4. Database returns some data
  5. REST API code packs up the data into Json and sends it to your client
  6. Client receives Json/XML response
  7. Map response to an object in your code

On the other hand, querying a database directly:

  1. You make an object with query string to query the database
  2. Database returns some data
  3. Map response to an object in your code

So wouldn't this mean that using a REST API would be slower? Maybe it depends on the type of database (SQL vs NoSQL)?

Best Answer

When you add complexity the code will run slower. Introducing a REST service if it's not required will slow the execution down as the system is doing more.

Abstracting the database is good practice. If you're worried about speed you could look into caching the data in memory so that the database doesn't need to be touched to handle the request.

Before optimizing performance though I'd look into what problem you're trying to solve and the architecture you're using, I'm struggling to think of a situation where the database options would be direct access vs REST.