Serving PHP session files from a RAM based disk (tmpfs) for AWS Micro Instances

It's rare to find a web server with slow disk I/O performance, but Amazon's EC2 micro-instances are one such example. Their EBS disk subsystem access is rated "low", and this can have a detrimental effect on HTTP throughput. Static resources can be cached in memory or pushed to CDN, and dynamic pages can be cached with APC (setting apc_stat off on production servers also provides in-memory caching for interpreted PHP bytecode). Also access and error logs can be written to the rsyslog daemon, which will perform asynchronous disk writes or forward logs to a central server.

This leaves sessions, which can be written to a redundant and fault tolerant storage system. But if sessions are stateless, only storing small amounts of reconstructable data (a user ID for example) they do not need redundancy, and writing to disk is acceptable. In order to speed up the disk access, a RAM-based disk can be mounted over the session directory. This has the disadvantage of being volatile - the data is lost in case of a server reboot, or the mount point being unmounted. However if tolerable, storing sessions in RAM insulates the application from poor filesystem performance.

There are two filesystem types distributed with newer kernels: ramfs and tmpfs (kernel 2.4+, previously called shmfs).

One downside of ramfs is you can keep writing data into it until you fill up all memory, and the VM can't free it because the VM thinks that files should get written to backing store (rather than swap space), but ramfs hasn't got any backing store. Because of this, only root (or a trusted user) should be allowed write access to a ramfs mount. A ramfs derivative called tmpfs was created to add size limits, and the ability to write the data to swap space. Normal users can be allowed write access to tmpfs mounts.

source kernel.org

What

  • Saves PHP session data to RAM instead of disk

Why

  • Faster I/O on systems with low filesystem performance (i.e. Amazon EC2 Micro-Instances)
  • Insulate the application from slow disk subsystem

Risks

  • Session data is lost on reboot or remounting of filesystem (although online resize is possible)

How

  1. Stop webserver (in this case Apache) or prevent new sessions being created using the application


  2. Move the existing sessions directory
    mv /var/lib/php/session /var/lib/php/session.old
  3. Create a new mount point
    mkdir /var/lib/php/session
  4. Write the configuration to /etc/fstab
    echo "tmpfs /var/lib/php/session tmpfs defaults 0 0" >> /etc/fstab
  5. Mount the tmpfs filesystem
    mount /var/lib/php/session
  6. Copy the existing sessions into the new directory, preserving attributes with -p
    cp -p /var/lib/php/session.old/* /var/lib/php/session
  7. Set the permissions and owner for the new directory
    chown root:apache session -R
    chmod 770 session -R
  8. Restart the web server - existing sessions will be maintained