A simple optimization methods while building a website is to remove bottleneck operations. Slow operations are due to heavy works: rebuilding cache, batch operations, etc ... of course these heavy operations can be moved to cron jobs which run every X minutes.
Actually a cron job is not ideal for building cache, or other real time operations, as you need to wait for another cron job iteration. As a user point of view, this is not ideal, waiting for a result might take some time. Asynchronous task is the solution.
Asynchronous tasks can be handle by a Message Queue. A queue system accepts messages from the application (producer) and sends the message to a task (consumer). This simple concept allows running tasks in background and removing some bottlenecks from the web application. More over you have better control on how the application scale as more consumers can be added.
How Symfony2 helps?
Symfony2 has been built on top of many services aggregated inside a service container. Understanding this concept allows to leverage the power of Symfony2 and the reusability of services. The reusability is not only for other projects where you can share a common base code. In this case, the reusability is done inside the application. Let's take a real life example: The SonataPageBundle.
The SonataPageBundle can publish a snapshot of a page. This operation is handled by the
SnapshotManager::create method. This method takes some time and memory at runtime. More over the result does not require being visible directly after the user refreshes the browser.
The NotificationBundle is a solution to produce and consume messages in a standard way. Different messages queues backends are available:
runtime: direct call to the consumer, so no benefit but useful for testing purpose
doctrine: use database to store messages, decent starting point for a small amount of async tasks
rabbitmq: use the RabbitMQ engine to handle messaging, best performance
rabbitmq require a background task (
sonata:notification:start) to be started and supervised. This task is responsible to dispatch a message to the correct listener. This command can be started many times to consume more messages (useful if our application runs on many servers).
If you want to go deeper into this bundle please refers to:
- the documentation : sonata-project.org/bundles/notification/master/doc/index.html
- PageBundle integration: github.com/sonata-project/SonataMediaBundle/commit/fa34e9e9c93c2a3ea6a7aab02463eae78c5c7f82
- MediaBundle integration: github.com/sonata-project/SonataPageBundle/commit/471fa8b1cf37cf6190f6321e457952784d512023