Looking to hire Laravel developers? Try LaraJobs

laravel-polyglot maintained by chrisoprea

Description
Move a Laravel monolith to Go and Rust one operation at a time, behind protobuf contracts, with canaries, shadow comparison and fallbacks. Designed to be removed.
Last update
2026/12/05 15:45 (dev-main)
License
Downloads
0

Comments
comments powered by Disqus

Laravel Polyglot

Tests Latest Version License

Move your Laravel application to Laravel Go and Laravel Rust, one operation at a time.

No rewrite. No cut-over weekend. No second architecture to learn. Your PHP code keeps serving every request while the Go or Rust version is built next to it, with the same routes, jobs, queues and config you already know from Laravel. Then you move traffic with one line of configuration: 5% of tenants first, a shadow that compares answers in the background, an automatic fallback to PHP if the new service is down.

When the last operation has moved, you composer remove the package. Your Laravel Go and Laravel Rust applications never depended on it.

flowchart LR
    App["Laravel PHP app"] -->|"Polyglot::call()"| Bridge{{"Laravel Polyglot"}}
    Bridge -->|"95%"| PHP["PHP handler<br/>(your existing code)"]
    Bridge -->|"5% canary"| Go["Laravel Go app"]
    Bridge -.->|"shadow, compared on the queue"| Rust["Laravel Rust app"]

Why

Rewriting a Laravel monolith is the project that never ships. Moving it piece by piece usually means hand-written HTTP clients, feature flags scattered through controllers, JSON that drifts between languages and nobody quite sure what still runs on PHP.

Laravel Polyglot turns that into a routine:

  • One contract, three languages. Each operation is declared once in protobuf. PHP, Laravel Go and Laravel Rust use code generated from it, so request and response shapes cannot drift.
  • Same Laravel, faster runtime. Your native code is a normal Laravel Go or Laravel Rust app: routes, queued jobs, queue:work, retries and failed jobs. The team keeps its Laravel instincts.
  • Configuration moves traffic. Route an operation, a service or a whole domain. Canaries stick to a tenant, shadows run after the response, and fallbacks only happen when it is safe.
  • Sync and async. Polyglot::call() for request/response, Polyglot::dispatch() to put a job straight on a Laravel Go or Laravel Rust queue, with the result coming back to your PHP listeners.
  • Built to leave. polyglot:inventory and the readiness report tell you which PHP code you can delete, and when the bridge itself can go.

The 60-second tour

Here is one operation, billing.invoice.find, served three ways.

1. Today: your existing PHP code, marked with one attribute.

#[Handles('billing.invoice.find')]
#[MapError(ModelNotFoundException::class, ErrorCode::NotFound, 'invoice.not_found')]
class FindInvoice
{
    public function __invoke(FindRequest $request): FindResponse
    {
        $invoice = Invoice::findOrFail($request->getInvoiceId());

        return new FindResponse(['invoice_id' => $invoice->id, 'total_cents' => $invoice->total_cents]);
    }
}

2. Tomorrow: the same operation in Laravel Go.

func (s *InvoiceService) Find(ctx context.Context, req *invoicev1.FindRequest) (*invoicev1.FindResponse, error) {
	invoice, err := s.invoices.Find(ctx, req.GetInvoiceId())
	if err != nil {
		return nil, connect.NewError(connect.CodeNotFound, err)
	}

	return &invoicev1.FindResponse{InvoiceId: invoice.ID, TotalCents: invoice.TotalCents}, nil
}

...or in Laravel Rust.

fn find(request: FindRequest) -> Result<FindResponse, DomainError> {
    let invoice = invoices::find(&request.invoice_id)?;

    Ok(FindResponse { invoice_id: invoice.id, total_cents: invoice.total_cents })
}

3. The switch: configuration, not code.

'billing.invoice.find' => [
    'use' => 'php',
    'canary' => ['use' => 'go', 'percentage' => 5, 'by' => 'tenant'],
    'shadow' => ['use' => 'rust', 'percentage' => 10],
],

Your controllers never change. They call the operation, not the implementation:

Polyglot::call('billing.invoice.find', new FindRequest(['invoice_id' => $id]));

Requirements

  • PHP 8.2+ with ext-bcmath or ext-protobuf
  • Laravel 12 or 13
  • buf to generate code from the contracts
  • For the native side: Laravel Go (go.laravel.com v0.1.1, Go 1.27) and/or Laravel Rust (laravel-rust =0.1.5). Both are in beta, so pin exact versions. Plain Go services work too.

Installation

composer require chrisoprea/laravel-polyglot

php artisan vendor:publish --tag=polyglot-config

Step by step

The rest of this guide moves billing.invoice.find (synchronous) and billing.invoice.export (a queued job) from PHP to Laravel Go and Laravel Rust. Complete, runnable versions of every snippet live in examples.

1. Write the contract

Contracts live in your application, next to the bridge's own protocol, which the package ships in vendor/chrisoprea/laravel-polyglot/proto. Add a buf.yaml at the root of your project:

version: v2
modules:
  - path: contracts
  - path: vendor/chrisoprea/laravel-polyglot/proto
lint:
  use:
    - STANDARD
breaking:
  use:
    - WIRE_JSON

Declare each operation on an RPC method, in contracts/billing/invoice/v1/invoice.proto:

syntax = "proto3";

package billing.invoice.v1;

import "polyglot/options/v1/options.proto";

option php_metadata_namespace = "App\\Contracts\\Billing\\Invoice\\V1\\GPBMetadata";
option php_namespace = "App\\Contracts\\Billing\\Invoice\\V1";

service InvoiceService {
  rpc Find(FindRequest) returns (FindResponse) {
    option (polyglot.options.v1.operation) = {
      id: "billing.invoice.find"
      mode: EXECUTION_MODE_SYNC
      side_effects: SIDE_EFFECTS_NONE
      shadow_safe: true
      default_timeout_ms: 2000
    };
  }

  rpc Export(ExportRequest) returns (ExportResponse) {
    option (polyglot.options.v1.operation) = {
      id: "billing.invoice.export"
      mode: EXECUTION_MODE_ASYNC
      side_effects: SIDE_EFFECTS_IDEMPOTENT
    };
  }
}

message FindRequest {
  string invoice_id = 1;
}

message FindResponse {
  string invoice_id = 1;
  int64 total_cents = 2;
}

message ExportRequest {
  string invoice_id = 1;
}

message ExportResponse {
  string location = 1;
}

Timeouts, side effects and shadow comparison rules live in the contract, so every runtime reads the same ones.

2. Generate the code

For PHP, use this buf.gen.yaml, then add the generated namespace to your composer.json autoload:

version: v2
plugins:
  - remote: buf.build/protocolbuffers/php:v36.2
    out: gen/php
inputs:
  - directory: contracts
buf lint
buf generate
buf build contracts --exclude-imports --exclude-source-info -o gen/php/descriptor.json
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "App\\Contracts\\": "gen/php/App/Contracts/"
    }
}

Laravel Go generates with protocolbuffers/go and connectrpc/go, and Laravel Rust with prost and pbjson, from the same contracts. The buf.gen.yaml of this repository shows all three.

3. Mark the PHP implementation

use App\Contracts\Billing\Invoice\V1\FindRequest;
use App\Contracts\Billing\Invoice\V1\FindResponse;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Polyglot\Bridge\Attributes\Handles;
use Polyglot\Bridge\Attributes\MapError;
use Polyglot\Bridge\Core\Error\ErrorCode;

#[Handles('billing.invoice.find')]
#[MapError(ModelNotFoundException::class, ErrorCode::NotFound, 'invoice.not_found')]
class FindInvoice
{
    public function __invoke(FindRequest $request): FindResponse
    {
        $invoice = Invoice::findOrFail($request->getInvoiceId());

        return new FindResponse(['invoice_id' => $invoice->id, 'total_cents' => $invoice->total_cents]);
    }
}

Handlers are discovered in app/, and their signature is checked against the contract. Then call the operation, by injection or through the facade:

use Polyglot\Bridge\Attributes\Operation;
use Polyglot\Bridge\Core\OperationCall;
use Polyglot\Bridge\Laravel\Facades\Polyglot;

public function show(string $id, #[Operation('billing.invoice.find')] OperationCall $findInvoice)
{
    return $findInvoice(new FindRequest(['invoice_id' => $id]))->getTotalCents();
}

Polyglot::call('billing.invoice.find', new FindRequest(['invoice_id' => $id]));

Errors come back as a PolyglotException with the same code and reason, whichever runtime served the call.

4. Serve it from Laravel Go

Implement the generated Connect interface, and mount it on Laravel Go's bare routes:

package main

import (
	"net/http"

	"connectrpc.com/connect/v2"
	"connectrpc.com/connect/v2/connecthttp"
	laravel "go.laravel.com"
	"go.laravel.com/config"
	"go.laravel.com/routing"

	"app/gen/go/billing/invoice/v1/invoicev1connect"
)

func main() {
	server := connect.NewServer()
	invoicev1connect.RegisterInvoiceServiceHandler(server, NewInvoiceService())

	rpc := http.NewServeMux()
	connecthttp.Mount(rpc, server)

	laravel.Run(laravel.Options{
		Routes: laravel.Routes{
			Health: "/up",
			Bare: func(route *routing.Router, _ *config.Config) {
				for spec := range server.Specs() {
					route.Handle("POST "+spec.Procedure, rpc)
				}
			},
		},
	})
}

The same handler also serves gRPC and gRPC-Web, so your other Go services can call it natively. In production, set APP_URL to the hostname the bridge uses (for example http://billing:8080): Laravel Go rejects requests for any other host. See the full example.

5. Or serve it from Laravel Rust

Add one Axum route that speaks Connect JSON, and keep your business logic in a plain function:

use laravel::axum::body::Bytes;
use laravel::axum::http::{StatusCode, header};
use laravel::axum::response::{IntoResponse, Response};
use laravel::prelude::*;
use laravel::routing::Router;

async fn find_rpc(body: Bytes) -> Response {
    let Ok(request) = serde_json::from_slice::<FindRequest>(&body) else {
        return connect_error(Code::InvalidArgument, "request.malformed", "malformed JSON body");
    };

    match find(request) {
        Ok(response) => (
            StatusCode::OK,
            [(header::CONTENT_TYPE, "application/json")],
            serde_json::to_vec(&response).expect("serialize response"),
        )
            .into_response(),
        Err(DomainError { code, reason, message }) => connect_error(code, reason, message),
    }
}

fn rpc(route: &mut Router) {
    route.post("/billing.invoice.v1.InvoiceService/Find", find_rpc);
}

fn main() -> ExitCode {
    Application::configure()
        .with_routing(|routing, _| {
            routing.routes(rpc).health("/up");
        })
        .run()
}

connect_error renders the Connect error format with the contract's error detail, in about 30 lines you can copy from the full example.

6. Route the traffic

Declare where your native applications live:

'endpoints' => [
    'go' => [
        'url' => env('POLYGLOT_GO_URL'),
        'token' => env('POLYGLOT_GO_TOKEN'),
        'serves' => ['billing'],
    ],
    'rust' => [
        'url' => env('POLYGLOT_RUST_URL'),
        'token' => env('POLYGLOT_RUST_TOKEN'),
        'serves' => ['billing'],
    ],
],

Then move an operation (billing.invoice.find), a service (billing.invoice) or a whole domain (billing):

'routing' => [
    'operations' => [
        'billing.invoice.find' => ['use' => 'go', 'fallback' => 'php'],
    ],
],

The fallback to PHP runs only when the native call certainly did not run (unavailable or unimplemented), never after a timeout, so nothing executes twice. After 5 consecutive failures the endpoint's circuit opens for 30 seconds and calls fall back without waiting.

7. Roll out safely with canaries and shadows

'billing.invoice.find' => [
    'use' => 'php',
    'canary' => ['use' => 'go', 'percentage' => 5, 'by' => 'tenant', 'salt' => '2027-01'],
    'shadow' => ['use' => 'rust', 'percentage' => 10],
],
You want to Change
Try Laravel Go on 5% of tenants 'canary' => ['use' => 'go', 'percentage' => 5]
Promote it raise percentage, then 'use' => 'go'
Roll back instantly 'percentage' => 0
Pick a different set of tenants change the salt
Check Laravel Rust without serving its answers 'shadow' => ['use' => 'rust', 'percentage' => 10]

A canary sends a stable share of tenants (or correlation ids) to the candidate. A shadow calls the candidate on the queue after the response, for operations the contract declares shadow_safe, and compares both answers under the contract's compare rules. Every comparison fires a ShadowCompared event. Mismatches are logged with field paths, never values.

8. Move queued jobs to Laravel Go and Laravel Rust

Asynchronous operations keep their PHP listeners while the work moves to a native worker:

$requestId = Polyglot::dispatch('billing.invoice.export', new ExportRequest(['invoice_id' => $id]));

class InvoiceExports
{
    #[OnCompletion('billing.invoice.export')]
    public function exported(ExportResponse $result, string $requestId): void {}

    #[OnCompletion('billing.invoice.export')]
    public function failed(PolyglotException $error, string $requestId): void {}
}

Routed to PHP, the operation runs as a job on your queue. Routed to Laravel Go or Laravel Rust, it becomes an ordinary job on their Redis queue, run by their own queue:work:

'go' => [
    'url' => env('POLYGLOT_GO_URL'),
    'serves' => ['billing'],
    'queue' => [
        'driver' => 'laravel-native',
        'connection' => 'polyglot',
        'queue' => 'billing',
    ],
],

On the Laravel Go side it is a job struct like any other:

type ExportInvoice struct {
	Envelope string `json:"envelope"`
}

func (ExportInvoice) JobName() string { return "billing.invoice.export" }

func (j ExportInvoice) Handle(ctx context.Context) error {
	env, err := decodeEnvelope(j.Envelope)
	req := &invoicev1.ExportRequest{}
	if err == nil {
		err = env.GetPayload().UnmarshalTo(req)
	}
	if err != nil {
		return queue.Fail(err)
	}

	resp, err := invoices.Export(ctx, req)

	return report(ctx, completion(env, resp, err))
}

And on the Laravel Rust side:

#[derive(Queueable)]
pub struct ExportInvoice {
    pub envelope: String,
}

#[job(name = "billing.invoice.export", tries = 3, backoff = [1.seconds()])]
impl ExportInvoice {
    async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
        let Some((envelope, request)) = decode(&self.envelope) else {
            attempt.fail(laravel::Error::msg("undecodable envelope"));
            return Ok(());
        };

        let outcome = match export(request) {
            Ok(response) => Outcome::Result(Any { type_url: RESPONSE_TYPE.into(), value: response.encode_to_vec().into() }),
            Err(DomainError { code, reason, message }) => failure(&envelope, code, reason, message),
        };

        report(completion(&envelope, outcome)).await
    }
}

The envelope carries the request with its tenant, correlation id, deadline and idempotency key. completion turns the result or the contract error into an outcome, and report posts it to /polyglot/completions, authenticated with POLYGLOT_COMPLETIONS_TOKEN. Each outcome reaches your #[OnCompletion] listeners exactly once. Retries, backoff, timeouts and failed jobs stay the framework's. The helpers are a few dozen lines each, in the examples for Laravel Go and Laravel Rust.

The bridge's Redis connection must have no key prefix ('options' => ['prefix' => '']), because Laravel Go and Laravel Rust do not use one.

9. Watch it

Every execution fires an OperationExecuted event. With POLYGLOT_OPENTELEMETRY=true and open-telemetry/api installed, executions are traced end to end (the trace continues inside the Laravel Go or Laravel Rust app), and the polyglot.operation.duration, polyglot.shadow.comparisons and polyglot.shadow.mismatches metrics are recorded.

Commands

php artisan polyglot:list                 # operations, implementations, routes, handlers and listeners
php artisan polyglot:doctor [--ping]      # checks the configuration, the endpoints and the environment
php artisan polyglot:inventory [--check]  # writes polyglot.inventory.yaml with each operation's migration stage
php artisan polyglot:cache                # caches the registry, also run by `php artisan optimize`
php artisan polyglot:clear

Knowing when you are done

Commit polyglot.inventory.yaml and run polyglot:inventory --check in CI. The readiness report reads it and scans your native code:

go install github.com/chrisoprea/laravel-polyglot/tools/readiness@latest

readiness -inventory polyglot.inventory.yaml -source services/billing [-domain billing] [-format json] [-strict]
  • PHP-free: an operation is ready once PHP no longer serves it, backs it up, takes part in its canary or shadows it. The report names the PHP handler you can delete.
  • Bridge-free: native code is ready once it imports nothing from the bridge and reads no serialized PHP. Completions posted to the bridge are listed as a step to take before removing it.

Then composer remove chrisoprea/laravel-polyglot. Your Laravel Go and Laravel Rust apps keep talking to each other through the generated clients, exactly as before.

How it talks

  • Synchronous calls use the Connect protocol over plain HTTP with JSON. No ext-grpc, nothing to compile on your PHP servers. Laravel Go serves Connect, gRPC and gRPC-Web from the same handler. Laravel Rust serves Connect JSON.
  • Asynchronous jobs go through Redis in the Laravel Go and Laravel Rust queue format, with the request in a binary protobuf envelope. Results come back over HTTP.

Documentation

Testing

composer test

The same contract suite runs against PHP, Laravel Go and Laravel Rust, in Docker:

scripts/test-native.sh          # synchronous: PHP, Go and Laravel Rust
scripts/test-native-async.sh    # asynchronous: Laravel Go and Laravel Rust queue workers
scripts/test-native-direct.sh   # Go calling Go and Laravel Rust directly, without the bridge
scripts/contracts.sh            # lint the contracts and regenerate the protocol and the examples

Contributing

Contributions are welcome. Please read the contributing guide: releases are cut automatically from Conventional Commits.

Security

Please report vulnerabilities privately, as described in the security policy.

License

Laravel Polyglot is open-sourced software licensed under the MIT license.