Thursday, December 4, 2014

Preventing cache stampede when using Doctrine Cache

Wikipedia has short and clear article on the matter, cache stampede can be quite deadly, especially when you are rebooting your server, clearing your cache or having a midnight maintenance (cronjob).

Cache stampede, put simply, is when your process is trying to fetch an expensive cache entry, it is not there, and tries to build it, but a simultaneous process comes and does the same thing. This results in resource waste because of processes all trying to do the same thing, uselessly.

The trick is to put a lock on the cache entry and make the other processes wait. I use the trick of having a TTL for the cache calculation. This way, even if the server crashes or there is an exception, the lock will expire and another process will take over. This estimation is also used to calculate how much time to sleep while waiting.

This example uses Doctrine Cache as a global variable, but this should definitely be refactored (or change to another system).

Tuesday, December 2, 2014

Load Doctrine Fixtures when using Migrations in Symfony

Using app/console doctrine:migrations:migrate is really easy and trouble free for everybody, but those tables are often empty and they need some data to be of any use. A common example is a table of countries or user roles.

However, once a project is started, it is often hard to use fixtures because it messes with your data. The trick here is to load only the fixtures you need, only when needed by the migration. This way, a new developer starting with the project could simply run the migrations and have a database ready for testing.

Here is a simple way of loading those fixtures on postUp. You need to pass an array of initialized fixture classes, Doctrine will figure the way to order them by itself.

This is only a proof of concept, it would need some refactoring and testing to be production ready, but you can get the idea.

Monday, December 1, 2014

MySQL 5.7 and Wordpress problem

If you upgrade to MySQL 5.7, you may encounter bugs with legacy software. Wordpress, which I also consider some kind of legacy software, does not handle this very well with its default settings.

You may encounter the "Submit for review" bug where you cannot add new posts. It may be related to permissions, auto_increment and other stuff, but here is another case: bad date formats and invalid data altogether.

In MySQL <= 5.6, by default, invalid values are coalesced into valid ones when needed. For example, attempting to set a field NULL on a non-null string will result in empty string. Starting with MySQL 5.7, this is not permitted.

Hence, if you want to upgrade to 5.7 and use all the goodies, you should consider putting it in a more compatible mode, adding this to your /etc/my.cnf:

# Default:

See official documentation for complete information