Reduce cloud costs by memory efficient PHP programming

Stefan Pöltl
5 min readDec 22, 2022

In this post I will show you how you can optimize your PHP programs in terms of memory usage in the cloud. There are several ways you can control it and keep it low.

Cloud computing

The cloud allows you to run PHP code Serverless(cloud functions) or in Container based environments. The most important thing is to simplify your development and on the other hand to reduce your infrastructure costs.
For AWS Lambda functions, your pricing also depends on the storage used:

AWS Lambda pricing example

The same applies for AWS ECS Tasks, the more memory you use the more you pay:

Example for ECS Task prices calculation from AWS

Queue consumer workers

What I see a lot in PHP based projects are endless running daemons consuming messages from a queue. Guess what, PHP daemons break from time to time due to memory issues, because web request based driven developers are not used to code it this way. If you want to stick to a daemon based process use the good old Supervisor process control and you can write your code as you’re used to for a single request.

Another way to do it is cloud native. On AWS you have the possibility to consume messages from a queue via the Lambda(Serverless) approach, so a cloud function gets invoked automatically. The only thing you have to do is coding the message processing and the cloud handles anything else. You can utilize the Serverless framework for PHP with

Of course there are cases when you end up with a lot of invocations of the Lambda function based queue consumer that results in a higher bill than running an ECS task based daemon. You probably have to run the numbers before you decide the way to go. No matter which approach you choose, memory problems won’t be an issue anymore.

Measure memory of your scripts