Why I like to store config variables in Postgres

postgres tutorials

backend

Have you ever wanted to change a configuration parameter of your application and the only way to change it was to update its environment variables and restart / re-deploy the application which takes minutes?
But what if you needed to change the configuration quickly?

One overlooked solution I like to use for this problem is to store some configuration parameters inside a Postgres table. This approach is best suited for parameters that are not accessed very frequently and are not secrets.

Example

An example that enables you to turn your cron jobs on/off would look like this:

CREATE TABLE cron_jobs (
	name TEXT,
	enabled BOOLEAN
);

INSERT INTO cron_jobs (name, enabled) VALUES ('foo', TRUE);

To check if the job is enabled:

SELECT enabled FROM cron_jobs WHERE name = 'foo';

And then in your application code you run the job if its enabled or bail out if its not.

Why I like this

I like this solution due to its simplicity. Assuming you are already using Postgres in your application (as you should), it will be very simple to implement this and you most likely already have a convenient Postgres interface which you can use to update the config values.

If you need to access the parameter very frequently and the time it takes to query for it is a problem, you could use an in-memory cache.

Another advantage of this approach comes when you want to store more structured data in your configuration. Values of environment variables are always strings so if you want to store an array or a boolean value you will need to parse the string in your application which makes it prone to errors when specifying a value for the variable. If you store the config in Postgres you can enforce that the value is of a certain type and there is no room for error.