# Instrument a service

> Wrap your consume loop with the Kavach recorder, route clock, randomness, queries, config and effects through the env, and make your binary a replay host.

Instrumenting a service takes three changes. The examples are Go; every [SDK](https://www.thekavachlabs.com/docs/sdks) has the same three pieces under similar names.

1. Route everything nondeterministic in the handler through the `env`.
2. Wrap the consume loop in a **recorder**: one `Step` per input.
3. Make the binary a **replay host** with one line at the top of `main`.

## Before you start: map the state

Find the code that consumes inputs one at a time and folds them into state. That is the handler. Then list, for that code:

- every place it reads the clock or random numbers;
- every external system it queries (databases, caches, HTTP APIs);
- every feature flag or limit it reads;
- every effect it produces (writes, messages, emails, calls with side effects).

Each item on the list becomes one env call. The [`/kavach-setup`](https://www.thekavachlabs.com/docs/guides/ai-agents#the-five-skills) agent skill does this mapping for you and writes it to `.kavach/plan/state-map.md` for review before it changes any code.

## 1. Use the env in the handler

```go
import kavach "github.com/kavachlabs/kavach/sdk/go"

type Ledger struct {
	Balances map[string]int64
}

func (l *Ledger) Handle(env kavach.Env, in kavach.Input) error {
	var ev Event
	if err := json.Unmarshal(in.Data, &ev); err != nil {
		return fmt.Errorf("decode event: %w", err)
	}
	at := env.Now()                          // not time.Now()

	var txn [8]byte
	if _, err := env.Read(txn[:]); err != nil { // not crypto/rand
		return err
	}

	rate, err := env.Query("fx-rates", []byte(ev.Currency)) // not an HTTP call
	if err != nil {
		return err
	}
	limit, _ := env.Config("MAX_TRANSFER")   // not os.Getenv

	// ... update l.Balances ...

	env.Emit("ledger.entries", entryJSON)    // not a direct database write
	return nil
}
```

Rules that keep replay exact:

- **Nothing nondeterministic outside the env.** No `time.Now`, `math/rand`, `os.Getenv`, direct network calls or direct writes inside the handler.
- **Reads in a deterministic order.** One at a time, in an order that does not depend on timing. (The TypeScript SDK reserves a query's journal position when `query()` is called, so `Promise.all` is safe.)
- **One step at a time.** Handlers are called from one thread or goroutine at a time.
- **Failure messages without addresses.** A returned error or panic message is compared on replay, so keep file paths, line numbers and pointer values out of it. Put them in the marker data instead (the stack trace is recorded there automatically).

## 2. Wrap the consume loop

```go
rec := kavach.NewRecorder(&Ledger{Balances: map[string]int64{}}, kavach.Options{
	Service: "ledger",
	Dir:     "kavach", // journals; fixtures go to kavach/fixtures/
	Gateway: func(gateway string, req []byte) ([]byte, error) {
		return fxClient.Get(req) // the real call, made and recorded live
	},
	Deliver: func(outs []kavach.Output) error {
		for _, o := range outs {
			if err := sinks.Write(o.Sink, o.Data); err != nil {
				return err
			}
		}
		return nil
	},
})
defer rec.Close()

for msg := range consumer.Messages() {
	if err := rec.Step(kavach.Input{
		Source:   "kafka:wallet-events",
		Position: fmt.Sprintf("%d:%d", msg.Partition, msg.Offset),
		Data:     msg.Value,
	}); err != nil {
		log.Printf("step failed: %v", err) // a fixture has been written
	}
}
```

The recorder writes the `input` record before calling the handler, so even a crash that kills the process leaves a complete record. Outputs reach `Deliver` only after the step succeeds.

Useful options:

| Option | What it does |
| --- | --- |
| `Gateway` | Makes real queries live; each request and response is recorded at the connection, below parsing, so a parsing bug replays. |
| `Config` | Where config values come from. Defaults to environment variables. |
| `Flags` | Feature flags to record in the environment record (`flag.<name>`). |
| `Start: journal.StartSnapshot` | Start the journal from a snapshot instead of genesis. Needs `Snapshot`/`Restore`. |
| `OnFixture` | Called with the path of every fixture written, for alerting or upload. |
| `SecretKeys` | Extra environment variable names whose values the recorder hashes in the environment record. |
| `RecoverPanics` | Return a `*PanicError` from `Step` instead of re-panicking. |

If the recorder cannot start, or stops, the SDK logs it and keeps stepping unrecorded. Recording never takes the service down.

## 3. Make the binary a host

```go
func main() {
	kavach.MaybeReplay(func() kavach.Handler { return &Ledger{Balances: map[string]int64{}} })
	// ... normal startup ...
}
```

When the last argument is `kavach-host`, `MaybeReplay` serves replay on stdin and stdout and exits; otherwise it returns immediately. Now `kavach replay fixture.kavach --bin ./ledger` works.

Pass the same gateway names to host mode in SDKs that ask for them; during replay the answers come from the fixture and the real system is never called.

## 4. Add snapshots and invariants (optional)

```go
func (l *Ledger) Snapshot() ([]byte, error) { return json.Marshal(l) }
func (l *Ledger) Restore(b []byte) error    { return json.Unmarshal(b, l) }

func (l *Ledger) Invariants() []kavach.Invariant {
	return []kavach.Invariant{
		{Name: "balances_non_negative", Check: func() error {
			for a, b := range l.Balances {
				if b < 0 {
					return fmt.Errorf("account %s has balance %d", a, b)
				}
			}
			return nil
		}},
	}
}
```

With `Snapshot` and `Restore`, fixtures start from recent state instead of the first event. With `Invariants`, a step that leaves state broken is recorded as a failure even if it did not crash. See [Write invariants](https://www.thekavachlabs.com/docs/guides/invariants).

## 5. Check it end to end

1. Feed the service an input that makes the handler fail (return an error is enough).
2. Look for the log line `kavach: wrote fixture …`.
3. `kavach replay <fixture> --bin <your host command>` should print `still_failing@N`.

If replay reports `nondeterministic@N`, the handler read time or randomness outside the env, or in a different order. If it reports `diverged@N`, an earlier step produced different outputs than production: look for state the handler reads that is not in the journal.

## Next

- Language specifics: [Go](https://www.thekavachlabs.com/docs/sdks/go), [Python](https://www.thekavachlabs.com/docs/sdks/python), [TypeScript](https://www.thekavachlabs.com/docs/sdks/typescript), [other languages](https://www.thekavachlabs.com/docs/sdks/other-languages).
- [Fix an incident](https://www.thekavachlabs.com/docs/guides/fix-an-incident) once you have a fixture.

Source: https://www.thekavachlabs.com/docs/guides/instrument-a-service
