# Process Initializers

> Code which runs when a sandbox process of your account starts, before any API - subscribe to MQTT or Redis, warm a cache, prepare a client - with the same g as a custom API.

Source: https://docs.apimaker.dev/v1/docs/features/process-initializers.html

A process initializer runs when a sandbox process of your account starts, before it serves any of your code. It is the place for work which must exist in every process : a subscription to a message broker, a client kept for the life of the process, a warm cache.

| | |
|---|---|
| Page | `API Info → Process Initializers` : name, order, timeout in minutes, active, and the code. |
| Runs | In every sandbox process, when it starts ; the active initializers in the order given, one after the other. |
| Code | `async function main(g: T.IAMGlobal)`, the same `g` as a custom API. |
| Test | **Test API** runs it on the API testing page. |

**Subscribe to a topic and write the messages**

```typescript
import * as T from 'types';
import * as mqtt from 'mqtt';   // added on the Sandbox Settings page

async function main(g: T.IAMGlobal) {
    const client = mqtt.connect(await g.sys.system.getSecret('mqtt.url'));
    client.on('message', async (topic, payload) => {
        await g.sys.db.saveSingleOrMultiple({ instance: 'mongodb', database: 'shop', collection: 'telemetry', saveData: { topic, payload: payload.toString(), at: new Date() } });
    });
    client.subscribe('shop/#');
    g.shared.mqtt = client;   // reachable by the code of this process
}
module.exports = main;
```

- Other code runs on an action : an HTTP call, a schedule, an event. An initializer runs on its own, once per process, so keep it light and idempotent.
- The number of sandbox processes is set on the [Sandbox Settings](https://docs.apimaker.dev/v1/docs/settings/sandboxSettings.html) page : each one runs the initializers.

## Related

- [Sandbox settings](https://docs.apimaker.dev/v1/docs/settings/sandboxSettings.html) · [The global object g](https://docs.apimaker.dev/v1/docs/pre-defined-terms/global-object-g.html) · [Schedulers](https://docs.apimaker.dev/v1/docs/apis-all/schedulers/user-created-schedulers-api.html)
