PeaBox Lab › PeaLang › Learn › Chapter 15 › Lesson 3

Part III — Advanced Systems · Chapter 15 · Lesson 3 of 7 · 8 min read

Lesson 3: Java 17 Sidecar Runtime and Client

Lesson level: Advanced

Purpose: Serve PeaLang rules to a Java 17 application through a sidecar process, with a typed client, timeouts, retries, health checks, and contract validation on the Java side.

Learning objectives

By the end of this lesson you will be able to:

3.1 Why a sidecar for Java

The reference PeaLang runtime is a Python package, so a JVM cannot load it in-process. The sidecar runs the runtime as a small local service next to the Java application. Java sends a portable-value request over HTTP on the loopback interface and receives a portable-value response. The JVM never executes PeaLang code itself, which also keeps the two processes’ failures separate.

The extra hop typically costs one to three milliseconds on the same host. For order and pricing services that already make database calls, that is usually acceptable. If it is not, consider moving the rule evaluation into a Python service that the Java application already calls.

3.2 Sidecar configuration

# sidecar/pea-sidecar.toml
[server]
bind = "127.0.0.1:7071"
max_body_bytes = 262_144
request_timeout_ms = 200
auth_token_env = "PEA_SIDECAR_TOKEN"

[modules.pricing]
artifact = "/opt/rules/pricing-2.3.0.peac"
contract = "/opt/rules/pricing.contract.toml"
exports = ["quote"]

[modules.pricing.runtime]
permissions = ["tier.read"]
max_execution_ms = 50
max_instructions = 200_000
max_http_requests = 0
max_file_read_bytes = 0
allow_process = false

[host_functions."host.lookup_tier"]
permission = "tier.read"
callback_url = "http://127.0.0.1:8080/internal/tiers/{customer_id}"
timeout_ms = 30

Three settings deserve attention. bind uses the loopback address, so nothing outside the machine or pod can reach the sidecar. auth_token_env requires a shared secret on every request, so other local processes cannot call it either. host_functions routes the script’s tier lookup back to an internal Java endpoint: the Java application still owns the data, while the sidecar only relays a validated call.

Start it with:

PEA_SIDECAR_TOKEN=$(cat /run/secrets/pea_token) \
    pea sidecar serve --config sidecar/pea-sidecar.toml

3.3 The call protocol

Each call is one HTTP POST with a JSON body of portable values. The response is either a result or a structured error, never a stack trace.

POST /v1/modules/pricing/exports/quote
Authorization: Bearer <token>
X-Request-Id: 7c1e...
Content-Type: application/json

{"args": [{"customer_id": "C000123", "currency": "EUR",
           "items": [{"sku": "A1", "qty": 2, "price": 9.99}]}]}

200 OK
{"result": {"subtotal": 19.98, "discount_pct": 15, "reason": "GOLD_100"},
 "module_version": "2.3.0",
 "usage": {"instructions": 3120, "elapsed_ms": 1.4}}

429 Too Many Requests
{"error": {"code": "PEA_RESOURCE_LIMIT", "message": "instruction limit exceeded"},
 "module_version": "2.3.0"}

Every response carries module_version, so the Java side can log exactly which rule produced each decision and detect a mismatch with the contract it was built against.

3.4 Java domain records

// pricing/*.java  (shown together; one public type per file)
package com.example.pricing;

import java.math.BigDecimal;
import java.util.List;

public record LineItem(String sku, int qty, BigDecimal price) {}

public record Cart(String customerId, Currency currency, List<LineItem> items) {}

public enum Currency { EUR, GBP, USD }

public record Quote(BigDecimal subtotal, BigDecimal discountPct, String reason,
                    String moduleVersion) {}

Records give immutable, value-based types with almost no code. As in Python, money uses BigDecimal on the host side and is converted only at the boundary.

3.5 A typed client

// pricing/PricingClient.java
package com.example.pricing;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.*;

public final class PricingClient {
    private static final ObjectMapper JSON = new ObjectMapper();
    private final HttpClient http = HttpClient.newBuilder()
            .connectTimeout(Duration.ofMillis(50)).build();
    private final URI endpoint;
    private final String token;
    private final CircuitBreaker breaker;

    public PricingClient(URI base, String token, CircuitBreaker breaker) {
        this.endpoint = base.resolve("/v1/modules/pricing/exports/quote");
        this.token = token;
        this.breaker = breaker;
    }

    public Quote quote(Cart cart, String requestId) {
        PricingContract.checkInput(cart);
        Map<String, Object> body = Map.of("args", List.of(toPortable(cart)));
        return breaker.call(() -> send(body, requestId, 2));
    }

    private Quote send(Map<String, Object> body, String requestId, int attempts) {
        for (int i = 1; ; i++) {
            try {
                HttpRequest req = HttpRequest.newBuilder(endpoint)
                        .timeout(Duration.ofMillis(150))
                        .header("Authorization", "Bearer " + token)
                        .header("X-Request-Id", requestId)
                        .header("Content-Type", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body)))
                        .build();
                HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
                JsonNode node = JSON.readTree(res.body());
                if (res.statusCode() == 200) {
                    return PricingContract.checkOutput(node.get("result"),
                            node.get("module_version").asText());
                }
                throw PricingErrors.from(res.statusCode(), node.path("error"));
            } catch (PricingErrors.Retryable e) {
                if (i >= attempts) throw e;
            } catch (java.io.IOException e) {
                if (i >= attempts) throw new PricingErrors.Unavailable("SIDECAR_IO", e);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new PricingErrors.Unavailable("INTERRUPTED", e);
            }
        }
    }

    private static Map<String, Object> toPortable(Cart cart) {
        List<Map<String, Object>> items = new ArrayList<>();
        for (LineItem it : cart.items()) {
            items.add(Map.of("sku", it.sku(), "qty", it.qty(),
                             "price", it.price().doubleValue()));
        }
        return Map.of("customer_id", cart.customerId(),
                      "currency", cart.currency().name(), "items", items);
    }
}

The client validates input before sending, validates output after receiving, retries only errors marked retryable, and wraps everything in a circuit breaker. Only two attempts are made: rules are fast, and more retries would multiply load during an outage.

3.6 Mapping sidecar errors

Sidecar status / codeJava exceptionRetry?Action
400 PEA_EXTENSION_ERRORRuleDefectNoAlert rule owner
400 INVALID_INPUTInvalidCartNoReturn 400 to caller
403 PEA_PERMISSION_DENIEDRuleDefectNoAlert rule owner; security review
429 PEA_RESOURCE_LIMITRuleDefectNoAlert rule owner; check limits
503 SIDECAR_STARTINGRetryableYesRetry once, then fail
I/O error or timeoutUnavailableYes, onceFallback or 503 to caller
200 with out-of-contract resultRuleDefectNoAlert rule owner
// pricing/PricingErrors.java
public final class PricingErrors {
    public static class PricingException extends RuntimeException {
        public final String code;
        PricingException(String code, Throwable cause) { super(code, cause); this.code = code; }
    }
    public static final class InvalidCart extends PricingException {
        InvalidCart(String code) { super(code, null); } }
    public static final class RuleDefect extends PricingException {
        RuleDefect(String code) { super(code, null); } }
    public static class Unavailable extends PricingException {
        Unavailable(String code, Throwable c) { super(code, c); } }
    public static final class Retryable extends Unavailable {
        Retryable(String code) { super(code, null); } }

    static PricingException from(int status, JsonNode err) {
        String code = err.path("code").asText("UNKNOWN");
        if (status == 503) return new Retryable(code);
        if (code.equals("INVALID_INPUT")) return new InvalidCart(code);
        return new RuleDefect(code);
    }
}

The sidecar’s message text is deliberately discarded. Only the stable code crosses into Java, so a rule cannot smuggle internal details into Java logs or API responses through an error message.

3.7 Health, readiness, and version checks

The sidecar exposes /healthz for liveness and /readyz for readiness. Readiness returns the loaded module versions. The Java application should not report itself ready until the sidecar is ready and serving the contract version it was built against.

// pricing/SidecarReadiness.java
public boolean ready() {
    JsonNode r = getJson("/readyz");
    String v = r.path("modules").path("pricing").path("version").asText("");
    return r.path("ready").asBoolean(false) && v.startsWith("2.");
}

The major-version check implements the compatibility rule from Lesson 1: any 2.x pricing module is acceptable to a client built against 2.3, but a 3.x module is not.

3.8 Deploying side by side

In a container platform, run the Java application and the sidecar as two containers in the same pod or task. They share the loopback network but have separate resource limits, so a runaway rule cannot starve the JVM.

containers:
  - name: orders
    image: registry.example.com/orders:4.12.0
    env:
      - { name: PEA_SIDECAR_URL, value: "http://127.0.0.1:7071" }
    resources: { limits: { cpu: "1", memory: "1Gi" } }
  - name: pea-sidecar
    image: registry.example.com/pea-sidecar:0.63.0rc2
    args: ["sidecar", "serve", "--config", "/etc/pea/pea-sidecar.toml"]
    resources: { limits: { cpu: "500m", memory: "256Mi" } }
    readinessProbe: { httpGet: { path: /readyz, port: 7071 } }
    securityContext:
      runAsNonRoot: true
      readOnlyRootFilesystem: true
      allowPrivilegeEscalation: false

Chapter 22 covers these security settings in depth. For now, note that the sidecar needs no write access and no network access beyond loopback.

3.9 Common mistakes

MistakeConsequenceFix
Binding the sidecar to 0.0.0.0Rules callable from the networkBind to 127.0.0.1 and require a token
Unlimited client retriesRetry storms during outagesTwo attempts plus a circuit breaker
Retrying rule defectsSame failure repeated; more loadRetry only Retryable errors
Logging sidecar error messagesInternal details leak into Java logsLog codes and request IDs only
Ignoring module_versionCannot trace which rule decidedStore the version with every decision
Shared CPU limits for both containersA busy rule starves the JVMSeparate resource limits per container
Marking the app ready before the sidecarEarly requests failGate readiness on sidecar readiness and version

Guided practice

Hands-on lab

Run the sidecar with the pricing module and build the Java client against it. Add a JUnit suite that starts the sidecar in a test container, covers every row of the error table, and verifies that the circuit breaker opens after five consecutive failures and closes after the sidecar recovers.

Deliverable: sidecar configuration, Java client and error classes, JUnit results, and a latency report.

Review questions

Applied challenge

Replace HTTP with gRPC for the sidecar call. Define the protobuf messages so they still carry only portable values, measure the latency difference, and decide whether the gain justifies the extra tooling for this service.

Lesson summary

A sidecar lets any host language use PeaLang rules through a local, authenticated, least-privilege service. The Java client validates both directions, maps stable error codes to typed exceptions, retries narrowly, and protects itself with a circuit breaker. Readiness and version checks tie deployment to the contract, and separate containers keep failures and resource use apart.

Transition to Lesson 4

Lesson 4 brings the same contract to TypeScript, first as a server-side client and then inside a React interface.

Lesson status: Ready for review.

← Previous Next →