Keep good frontend performance with API on top of FOSRestBundle

FOSRestBundle is probably the best bundle providing features and tools for creating REST API in your Symfony application. But from other side it’s very big and full of listeners bundle. I will write today about case when we have API and frontend/backoffice in this same app (and environment), and how to make sure that FOSRestBundle will not slow down other part of application - as it do this by default.

First let’s look at list of FOSRestBundle listeners:

  • View Response Listener
  • Body Listener
  • Request Body Converter Listener
  • Format Listener
  • Versioning
  • Mime Type Listener
  • Param Fetcher Listener
  • Allowed Http Methods Listener
  • Security Exception Listener

It’s long list and if enabled — those listeners will be called on every request. Also on those not connected to API. It may conflict with other parts of your application. And for sure is bad thing for performance.

From version 2.0.0 (currently tagged 2.0.0-BETA2) we can use zones feature.

Zones feature provide for us one more listener - ZoneMatcherListener. This listener check if requested url’s i covered by any zone and save special parameter to Request attributes. From now if this attribute is false then all listeners will return false as soon as possible.

Here is example from ViewResponseListener

But ViewResponseListener (and looks like it’s only this listener) can still create some performance loss. Why? Because even if we return false at very beginning of onKernelView action - we still load heavy viewHandler service in listener constructor.

Only (know by me) way to preventing that is disabling that listener (it will not be created in container) and returning FOS\RestBundle\View manually from controller actions.