Skip to content
Kavach Labs
How it worksAtlasAtlasPricingPricingDocsDocsBlogBlogReleasesReleases
3
Esc

    ↑ ↓ to move↵ to open

    Get started

    • Overview
    • Installation
    • Quickstart
    • Concepts

    Guides

    • Instrument a service
    • Fix an incident
    • Build a feature
    • Write invariants
    • Run in CI
    • Flow maps
    • Use with AI agents

    SDKs

    • Overview
    • Go
    • Python
    • TypeScript
    • Other languages
    • No SDK? Use the protocols

    Reference

    • CLI
    • Verdicts
    • MCP tools
    • map.json
    • Journal format
    • Troubleshooting

    Benchmark

    • Methodology

    Enterprise

    • Overview
    • Install and upgrade
    • Deploy
    • Storage
    • Operations
    • Security
    • Data handling
    DocsOther languages

    Get started

    • Overview
    • Installation
    • Quickstart
    • Concepts

    Guides

    • Instrument a service
    • Fix an incident
    • Build a feature
    • Write invariants
    • Run in CI
    • Flow maps
    • Use with AI agents

    SDKs

    • Overview
    • Go
    • Python
    • TypeScript
    • Other languages
    • No SDK? Use the protocols

    Reference

    • CLI
    • Verdicts
    • MCP tools
    • map.json
    • Journal format
    • Troubleshooting

    Benchmark

    • Methodology

    Enterprise

    • Overview
    • Install and upgrade
    • Deploy
    • Storage
    • Operations
    • Security
    • Data handling
    Kavach Labs

    A flight recorder for production software.

    Product

    How it worksPricingFor agentsAgent benchmarkRelease notes

    Developers

    DocsQuickstartSDKsCLI referenceAgent skillsEnterpriseBenchmarksSource

    Project

    BlogLicenseReport a bug
    © 2026 Kavach LabsPre-alpha · Apache 2.0
    Docs/SDKs

    Other language SDKs

    Rust, Java, C and C++, Ruby, PHP, Elixir, Haskell, OCaml and Julia. Each has a handler, a recorder and a one-line host mode, and replays through the same CLI.

    kavach v0.2.0

    Every SDK below follows the same shape: a handler that uses only its env, a recorder around the consume loop, and a maybe_host call at the top of main. Each ships a port of the quickstart ledger. Install from a checkout of the Kavach repository; none is on a package registry yet.

    Rust#

    Rust 1.75+, Unix, no runtime dependencies, synchronous API (tokio support is planned).

    [dependencies]
    kavach = { path = "sdk/rust" }
    use kavach::{Env, Handler, HandlerResult, HostOptions, Input, Recorder, Scope};
     
    struct Ledger { balance: i64 }
     
    impl Handler for Ledger {
        fn handle(&mut self, env: &mut dyn Env, input: &Input) -> HandlerResult {
            let at = env.now_nanos();
            let mut txn = [0u8; 8];
            env.fill_random(&mut txn);
            let rate = env.query("fx-rates", b"EURUSD")?;     // Result<Vec<u8>, GatewayError>
            let limit = env.config("MAX_TRANSFER");          // Option<Vec<u8>>
            env.emit("ledger.entries", b"...", Scope::Remote);
            Ok(())
        }
    }
     
    fn main() {
        kavach::maybe_host(|| Box::new(Ledger { balance: 0 }), HostOptions::new());
        let mut rec = Recorder::builder("ledger")
            .dir("kavach")
            .deliver(|outs| { /* write outs */ Ok(()) })
            .build(Box::new(Ledger { balance: 0 }))
            .expect("recorder");
        // for each input: rec.step(&Input::new(source, position, data))
    }

    Snapshots and invariants: implement Snapshotter / Checker and override Handler::snapshotter / Handler::checker to return Some(self). A panic is caught at the step boundary and recorded, then keeps unwinding unless recover_panics(true). With panic = "abort" the recorder records a crash.

    kavach replay incident.kavach --bin ./target/release/ledger

    Java#

    Java 21+, JDK only. Package com.kavachlabs.kavach. Build with ./build.sh in sdk/java (produces build/kavach.jar).

    import com.kavachlabs.kavach.*;
    import java.time.Instant;
    import java.util.List;
    import java.util.Optional;
     
    final class Wallet implements Handler, Snapshotter {
        long balance;
     
        @Override
        public void handle(Env env, Input input) throws Exception {
            Instant now = env.now();                                    // env.nowNanos() for nanoseconds
            byte[] txn = env.random(8);                                 // never SecureRandom / Math.random
            byte[] rate = env.query("fx-rates", "EURUSD".getBytes());   // throws GatewayException
            Optional<byte[]> limit = env.config("MAX_TRANSFER");
            env.emit("postgres:balances", "...".getBytes());            // delivered after the step succeeds
        }
     
        @Override public byte[] snapshot() { return Long.toString(balance).getBytes(); }
        @Override public void restore(byte[] data) { balance = Long.parseLong(new String(data)); }
        @Override public List<Invariant> invariants() {
            return List.of(Invariant.of("non_negative", () -> balance >= 0));
        }
    }
     
    public final class Main {
        public static void main(String[] args) {
            Gateways gateways = new Gateways().register("fx-rates", req -> fxClient.get(req));
            Kavach.maybeHost(args, Wallet::new, HostOptions.defaults().gateways(gateways));
            // ... normal service
        }
    }
    kavach replay incident.kavach --bin "java -cp app.jar:kavach.jar com.example.Main"

    C and C++#

    libkavach is a C11 library with libc and pthreads only, for macOS and Linux. kavach.hpp is a header-only C++17 wrapper (RAII recorder, exceptions). Build with CMake: cmake -S sdk/c -B build && cmake --build build.

    #include <kavach/kavach.h>
     
    static int handle(void* state, kavach_env* env, const kavach_input* in) {
      int64_t now = kavach_now_ns(env);
      uint8_t id[8];
      kavach_random(env, id, sizeof id);
      uint8_t* rate; size_t n; char* err;
      if (kavach_query(env, "fx-rates", "EURUSD", 6, &rate, &n, &err) != KAVACH_OK) {
        int rc = kavach_errorf(env, "fx failed: %s", err);   /* error marker */
        kavach_free(err);
        return rc;
      }
      kavach_emit(env, "postgres:balances", rate, n, KAVACH_REMOTE);
      kavach_free(rate);
      return KAVACH_OK;
    }
     
    int main(int argc, char** argv) {
      kavach_maybe_host(argc, argv, make_handler, &host_opts);   /* first */
      /* kavach_recorder_new(...), then kavach_recorder_step(rec, &in, &res) per input */
    }
    #include <kavach/kavach.hpp>
     
    class Ledger : public kavach::Handler {
      void handle(kavach::Env& env, const kavach::Input& in) override {
        auto now = env.now_ns();
        kavach::Bytes id = env.random(8);
        auto q = env.query("fx-rates", "EURUSD");
        if (!q.ok) throw kavach::HandlerError("fx failed: " + q.error);
        env.emit("postgres:balances", q.response);
      }
    };
     
    int main(int argc, char** argv) {
      kavach::maybe_host(argc, argv, [] { return std::make_unique<Ledger>(); });
      Ledger ledger;
      kavach::RecorderOptions o; o.service = "ledger";
      kavach::Recorder rec(ledger, o);
      auto r = rec.step("kafka:wallet-events", "3:1042", bytes);
    }

    On macOS, build with clang.

    Ruby#

    Ruby 3.1+, no gem dependencies.

    # Gemfile
    gem "kavach", path: "path/to/kavach/sdk/ruby"
    require "kavach"
    require "time"
     
    class Counter
      def initialize = @n = 0
     
      def handle(env, input)
        at = env.now                                  # Time, UTC
        rate = env.query("fx-rates", "EURUSD")        # raises Kavach::GatewayError
        limit = env.config("MAX_TRANSFER")            # String or nil
        @n += 1
        env.emit("db:counts", "#{@n}@#{at.iso8601}")
      end
     
      def snapshot = @n.to_s
      def restore(data) = @n = data.to_i
      def invariants = [Kavach::Invariant.new("non_negative") { raise "negative" if @n.negative? }]
    end
     
    Kavach.maybe_host(gateways: gateways) { Counter.new }   # first thing in the program
    kavach replay incident.kavach --bin "ruby -Ilib service.rb"

    PHP#

    PHP 8.2+, no dependencies. For long-running CLI workers such as queue consumers; per-request recording under FPM is planned.

    require '/path/to/kavach/sdk/php/src/autoload.php';   // or Composer, as a path repository
     
    use Kavach\{Env, Handler, HasInvariants, Input, Invariant, Snapshotter};
     
    final class Wallet implements Handler, Snapshotter, HasInvariants
    {
        private int $balance = 0;
     
        public function handle(Env $env, Input $input): void
        {
            $now   = $env->now();                         // UTC DateTimeImmutable
            $txn   = bin2hex($env->random(8));            // never random_bytes()
            $rate  = $env->query('fx-rates', 'EURUSD');   // throws Kavach\GatewayError
            $limit = $env->config('MAX_TRANSFER');        // ?string
            $env->emit('postgres:balances', '...');
        }
     
        public function snapshot(): string { return (string) $this->balance; }
        public function restore(string $data): void { $this->balance = (int) $data; }
        public function invariants(): array
        {
            return [new Invariant('non_negative', fn () => $this->balance >= 0)];
        }
    }
     
    Kavach\maybeHost($argv, fn () => new Wallet(), ['gateways' => [/* ... */]]);
    kavach replay incident.kavach --bin "php worker.php"

    Elixir#

    Elixir 1.15+, standard library only. A handler is a behaviour with explicit state, in the shape of a GenServer.

    defmodule Counter do
      @behaviour Kavach.Handler
     
      def init, do: 0
     
      def handle(env, %Kavach.Input{data: data}, n) do
        at = Kavach.Env.now(env)
        id = Kavach.Env.random(env, 8)
        Kavach.Env.emit(env, "log", "#{n} #{at} #{Base.encode16(id)}")
        if data == "bad", do: raise("boom"), else: {:ok, n + 1}
      end
     
      def snapshot(n), do: Integer.to_string(n)
      def restore(bin), do: String.to_integer(bin)
      def invariants(n), do: [{"non_negative", fn -> if n >= 0, do: :ok, else: {:error, "n=#{n}"} end}]
    end
     
    {:ok, rec} = Kavach.Recorder.start_link(handler: Counter, service: "counter")
    :ok = Kavach.Recorder.step(rec, %Kavach.Input{source: "queue", position: "0:1", data: "..."})

    Call Kavach.maybe_host(argv, MyHandler) first in the escript's main, build with mix escript.build, and give its path to --bin:

    kavach diff incident.kavach --old ./ledger --new "./ledger --fix"

    Haskell#

    GHC 9.4+, boot packages only. A handler runs in the Kavach monad, which has no MonadIO instance: the type checker guarantees the handler reaches the world only through Kavach's functions (now, random, query, config, emit).

    data Handler s = Handler
      { handle     :: Input -> s -> Kavach s
      , initial    :: s
      , snapshot   :: Maybe (s -> ByteString)
      , restore    :: Maybe (ByteString -> Either String s)
      , invariants :: [(Text, s -> Either Text ())]
      }
     
    main :: IO ()
    main = do
      maybeHost myHandler
      let opts = (defaultOptions "ledger") { roDeliver = mapM_ print }
      withRecorder opts myHandler $ \r -> do
        res <- step r (Input "kafka:wallet-events" "0:1042" bytes)
        pure ()
    kavach replay incident.kavach --bin "$(cabal list-bin ledger)"

    OCaml#

    OCaml 5.1+, only the compiler distribution's libraries. State is explicit: handle takes the state and returns the next one.

    module Counter : Kavach.HANDLER = struct
      type t = { mutable n : int }
      let init () = { n = 0 }
      let handle env (input : Kavach.Input.t) st =
        let at = Kavach.Env.now_ns env in
        Kavach.Env.emit env ~sink:"log" (Printf.sprintf "%Ld %s" at input.data);
        st.n <- st.n + 1;
        Ok st
      let snapshot = Some (fun st -> string_of_int st.n)
      let restore = Some (fun s -> { n = int_of_string s })
      let invariants = [ ("non_negative", fun st -> if st.n >= 0 then Ok () else Error "negative") ]
    end
     
    let () =
      Kavach.maybe_host (module Counter);
      let rec_ = Kavach.Recorder.create ~service:"ledger" (module Counter) in
      (* Kavach.Recorder.step rec_ { source; position; data } per input *)
      Kavach.Recorder.close rec_

    Julia#

    Julia 1.10+, standard library only. Define methods on your own type.

    using Kavach
     
    mutable struct Counter; n::Int; end
     
    function Kavach.handle!(h::Counter, env::Env, input::Input)
        h.n += 1
        at = Kavach.now(env)
        emit!(env, "log", "event $(h.n) at $at")
    end
     
    Kavach.snapshot(h::Counter) = Vector{UInt8}(codeunits(string(h.n)))
    Kavach.restore!(h::Counter, data) = (h.n = parse(Int, String(copy(data))))
    Kavach.invariants(h::Counter) = Pair{String,Function}["non_negative" => () -> h.n >= 0]
     
    Kavach.maybe_host(ARGS, () -> Counter(0))      # first in main
     
    rec = Recorder(Counter(0); service="counter", dir="kavach")
    step!(rec, Input("kafka:topic", "0:42", data))
    close(rec)
    kavach replay incident.kavach --bin "julia --project=. service.jl"

    After a one-time Pkg.precompile(), a Julia host is ready in about a quarter of a second.

    Something wrong or missing on this page? Report it on GitHub, or write to hello@thekavachlabs.com.

    PreviousTypeScriptNextNo SDK? Use the protocols

    On this page

    1. Rust
    2. Java
    3. C and C++
    4. Ruby
    5. PHP
    6. Elixir
    7. Haskell
    8. OCaml
    9. Julia
    View as Markdown