Drupal State API vs. Config API: Where to Store Runtime Flags and Environment Data
A common mistake in custom Drupal modules is storing a “last cron run” timestamp, an external API sync cursor, or a one-off maintenance flag inside mymodule.settings via the Configuration API. The moment you run drush cex, Git shows dirty YAML diffs for a timestamp that changes every hour—and deploying that file overwrites production’s runtime state with your local laptop’s timestamp. Drupal separates State from Configuration specifically to prevent that problem.
Editorial illustration: store machine-generated, per-environment values in the State API and human-edited, deployable settings in the Configuration API.
Summary
- Per Drupal’s State API overview, the State API (
\Drupal::state()) stores machine-generated, environment-specific information in the databasekey_valuetable and is never exported bydrush cexor deployed across environments. - Per Drupal’s Configuration API overview, the Configuration API stores human-edited site structure and settings (content types, views, site name, module settings) that should synchronize from development to production.
- Use State API for
cron_lasttimestamps, queue cursors, or temporary environment flags; remember that State values are lost if a database is dropped or reinstalled from config. - Never store API secrets inside exported Config YAML—use
settings.phpoverrides or environment variables instead.
How Drupal classifies information types
According to Drupal API’s Information types documentation, Drupal divides site data into four distinct buckets:
- Content: Articles, pages, users, media, and files (stored as Content Entities).
- Session: Per-user interaction state (accessed via Symfony’s session object).
- State: Temporary or machine-generated data tied to this specific database instance (for example, when cron last ran or whether node access permissions need rebuilding).
- Configuration: Permanent, human-edited settings meant to travel across dev, staging, and production via
config/sync.
Mixing bucket 3 into bucket 4 is what causes noisy drush cex diffs and accidental state overwrites during deployments.
Using the State API in custom services
In custom Drupal 10 and 11 code, inject the @state service (\Drupal\Core\State\StateInterface) rather than calling \Drupal::state() inside classes:
use Drupal\Core\State\StateInterface;
final class InventorySyncService {
public function __construct(
private readonly StateInterface $state,
) {}
public function getLastSyncTimestamp(): int {
return (int) $this->state->get('my_module.last_inventory_sync', 0);
}
public function markSynced(int $timestamp): void {
$this->state->set('my_module.last_inventory_sync', $timestamp);
}
}
Key behaviors to keep in mind:
- Always prefix keys with your module machine name (for example,
my_module.last_inventory_sync) to avoid collisions in the sharedkey_valuetable. - Provide a sensible default (
0,FALSE,[]) in$this->state->get($key, $default)so a freshly installed database fromconfig/syncworks cleanly even before the first sync runs. - Do not confuse State API with Form API
#states:#statesis a client-side JavaScript visibility helper on forms, completely unrelated toStateInterface.
When you still need Config API (or settings.php)
Use the Configuration API (config.factory) when an administrator configures behavior in admin/config and that exact behavior should ship to staging and production—for example, “how many items per page should this sync batch fetch?” or “which content type is enabled for notifications?”
If a configuration setting must differ per environment (such as a sandbox vs. production API endpoint or credentials), keep the base structure in Config API and override the environment-specific value in settings.php / settings.local.php, or use Configuration Split for environment-specific modules. For live-edited admin settings that should not be overwritten by drush cim, compare Config Ignore vs. Configuration Split.
Step-by-step: Clean up runtime state accidentally saved in config
- Inspect recent
drush cexdiffs. Look for keys likelast_run,cursor,token_expires, orsync_statusinsideconfig/sync/*.settings.yml. - Move reads and writes to
StateInterface. Replace$this->configFactory->getEditable(...)->set('last_run', ...)with$this->state->set('my_module.last_run', ...). - Remove the runtime key from your config schema and exported YAML. Export clean config via
drush cexand review the diff using a Drupal config import checklist. - Add an update hook if existing environments hold stale keys. Write a
hook_update_N()orhook_post_update_NAME()to migrate any needed existing value intoStateInterfaceand clean up the old config key.
Common mistakes
- Putting human-edited admin settings in State API just to avoid
drush cimoverwrites. If a site builder configures something in the UI and expects it to deploy from staging to production, State API will silently drop it on fresh installs. - Calling
StateInterface::set()insidehook_cron()with Configuration API instead. Even a tinycron_lasttimestamp inmymodule.settings.ymlforces Git merge conflicts across developers. - Forgetting that State API is not a cache. State entries persist in
key_valueuntil explicitly updated or deleted; for disposable computed data that can be rebuilt anytime, use Drupal’s Cache API (cache.default) with proper cache tags instead—see debugging Drupal cache tags.
Why this matters
Keeping runtime machine state out of config/sync makes drush cex and drush cim quiet, predictable, and easy to review in pull requests. Your deployment pipeline stays focused on intentional site changes rather than fighting timestamps.
My Take
Whenever you add a setting in a custom Drupal module, ask one question before writing code: “If we wipe this environment and reinstall from config/sync, should this value come back from Git, or start fresh from zero?” If it should come from Git, use Configuration API; if it belongs only to that running instance, use State API.
Conclusion
Inject StateInterface (@state) for machine-generated, per-environment values like sync timestamps and cursors, reserve the Configuration API for deployable settings, and audit config/sync for any runtime keys causing unnecessary drush cex diffs.