Introduction to Microservices in Laravel: A Basic Guide

- Andrés Cruz - ES En español

Video thumbnail

Content Index

This section addresses the design and implementation of a microservices architecture. Beyond the practical execution of the code—available via tags in the corresponding repository for review and testing—the main objective is to understand the fundamentals, technical rationale, and operational behavior of this type of system.

1. Fundamental Concepts and Service-to-Service Communication

A microservice is an independent application designed to solve a specific domain. In this initial implementation, the system is split into two main components:

  • User Service: Responsible for authentication, identity management, and credential issuance.
  • Task Service: Responsible for processing user operations, requiring prior validation against the authentication service for each action.

2. Challenges and Key Components in Microservices

As a distributed architecture grows, it is necessary to incorporate advanced control, security, and resiliency mechanisms:

  • Rate Limiting: Protection of endpoints through access restrictions to prevent abuse or denial of service.
  • Observability and Traceability: Implementation of unique identifiers (Correlation IDs) that allow tracking the flow of a request across multiple services, facilitating error diagnosis.
  • Modularization with Composer: Extraction of shared code into local packages to avoid duplication among similar services (such as the subsequent addition of the billing service or Billing Service).
  • Resiliency and Load Management: Mitigation of single points of failure and saturation during concurrent traffic spikes toward the central user service.
  • Authentication with JSON Web Tokens (JWT): Use of cryptographic tokens self-validated via public and private keys to optimize identity verification without overloading network queries.
  • Queues and Asynchronous Events: Utilization of specialized message brokers (such as RabbitMQ) to manage asynchronous communication and background task processing among services.

This overview introduces the necessary pillars to structure robust, scalable, and decoupled distributed systems. Understanding these architectural patterns lays the groundwork for building applications prepared for complex production environments.

Video thumbnail

In this post, we will explore the fundamental concepts of a microservices architecture using Laravel. To illustrate this model, we will develop a practical example consisting of two independent applications: a user service (user-service) and a task management service (task-service).

1. The Principle of Data Independence

Unlike a monolithic application, in a microservices architecture each service is completely independent and owns its persistence layer.

 user-servicetask-service
Porthttp://127.0.0.1:8000http://127.0.0.1:8001
Databasedatabase/db_users.sqlitedatabase/db_tasks.sqlite
Own tablesuserstasks, cache, jobs
Knows users?Yes, it is the ownerNo, it only stores the user_id
Knows tasks?NoYes, it is the owner
InterfaceNone (headless)REST API + Blade web UI

Synchronous HTTP communication between two independent Laravel microservices — and where it goes from here.

+-------------+      +-------------------------------------+      +------------------+
|             |      |                                     |      |                  |
|   Client    |----->|  task-service  (:8001)              |----->|  user-service    |
|   curl /    | POST |  db_tasks.sqlite                    |  GET |  (:8000)         |
|  Postman/UI |<-----|  Does NOT have the users table      |<-----|  db_users.sqlite |
|             | 201  |  validates user_id via HTTP         | 200  |  (headless)      |
+-------------+      +-------------------------------------+ 404  +------------------+

How to read this document: sections 1 to 11 = what is implemented and verified today. Sections 12 to 21 = what comes next, not implemented, it is a roadmap with the reasoning behind each decision.

There are no physical foreign keys (FOREIGN KEY) or JOIN joins between the databases of both services. In the task service, the user_id field is stored solely as a numeric identifier without distributed database constraints. And you can see this from the task migration:

task-service/database/migrations/2026_10_10_093642_create_tasks_table.php

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('title');

            // Logical reference to user-service. NOT a foreign key:
            // the users table lives in another database (db_users), in another
            // process and in another service. Integrity is validated via HTTP.
            $table->unsignedBigInteger('user_id')->index();

            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

2. Synchronous Communication via HTTP and the Service Client Pattern

To ensure a task is associated with a valid user, the task-service makes synchronous HTTP requests to the user-service using a dedicated client.

Encapsulation with UserServiceClient

All network communication logic is isolated in a service client that acts as a transparent boundary, allowing controllers to treat the external microservice as if it were a local function:

task-service/app/Services/UserServiceClient.php

namespace App\Services;

class UserServiceClient
{
    public function find(int $id): ?array
    {
        $response = $this->request("/api/users/{$id}");

        if ($response->status() === 404) {
            return null;
        }

        if ($response->failed()) {
            throw new UserServiceErrorException("The user-service responded with {$response->status()}.");
        }

        return $response->json();
    }

    public function all(): array
    {
        $response = $this->request('/api/users');

        if ($response->failed()) {
            throw new UserServiceErrorException("The user-service responded with {$response->status()} when listing users.");
        }

        return $response->json('data', []);
    }

    private function request(string $uri): Response
    {
        try {
            return Http::acceptJson()
                ->timeout($this->timeout())
                ->get($this->baseUrl().$uri);
        } catch (ConnectionException $exception) {
            throw new UserServiceUnavailableException('Could not contact the user-service.', previous: $exception);
        }
    }
}

3. User Service Endpoints

The user-service operates minimally by exposing a catalog of users in JSON format:

user-service/routes/api.php

Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show'])->whereNumber('id');

 user-service/app/Http/Controllers/UserController.php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;

class UserController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(User::query()->orderBy('name')->paginate(50));
    }

    public function show(int $id): JsonResponse
    {
        $user = User::query()->find($id);

        if (! $user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        return response()->json($user, 200);
    }
}

4. Task Management and Validation in TaskController

When processing the creation or updating of a task, the controller validates the user's existence by querying the remote service before persisting the information:

task-service/app/Http/Controllers/TaskController.php

public function store(StoreTaskRequest $request, UserServiceClient $userService): RedirectResponse
{
    $validated = $request->validated();

    if ($userService->find($validated['user_id']) === null) {
        throw ValidationException::withMessages([
            'user_id' => 'That user does not exist in the user-service.',
        ]);
    }

    Task::query()->create([
        ...$validated,
        'status' => $validated['status'] ?? Task::STATUS_PENDING,
    ]);

    return redirect()->route('tasks.index')->with('success', 'Task created successfully.');
}

Also, we implement the API-type service so it can be consumed through a dedicated application.

5. Considerations on Resilience and Graceful Degradation

When working in distributed environments, the failure or slowness of a dependent microservice must not completely crash the user interface. Mechanisms like Laravel's rescue function are implemented to allow a degraded experience:

public function show(Task $task, UserServiceClient $userService): View
{
    return view('tasks.show', [
        'task' => $task,
        // If the user-service does not respond, the task is shown without the owner's name
        'owner' => rescue(fn () => $userService->find($task->user_id), report: false),
    ]);
}

6. The complete workflow, step by step

  1. The client makes POST http://127.0.0.1:8001/api/tasks with { "title": "...", "user_id": 2 }.
  2. The task-service validates the payload (title required, user_id required/integer greater than or equal to 1). If it fails, it responds with 422 without touching the network.
  3. The task-service requests the list of users from the user-service (GET /api/users) to populate the form. Only in the web UI.
  4. When saving, the task-service opens an HTTP connection with Http::get towards http://127.0.0.1:8000/api/users/{id}.
  5. The user-service queries its own users table:
    • 200 with the JSON model: the user exists.
    • 404 with {"error":"User not found"}: the user does not exist.
  6. Depending on the response, the task-service decides:
    • 200: inserts the task into db_tasks and responds 201 with the created task.
    • 404: responds 422 and writes nothing.
    • Connection refused or timeout: responds 503.
    • Other status (500, 502): responds 502.

Everything is synchronous blocking: the client's request waits for the user-service to reply. This is the simplest model to explain; section 13 explains when and how to stop doing it this way.

7. Response Matrix

Situationuser-servicetask-serviceIs it saved?
Invalid payload-422 (validation)No
user_id exists200201 + taskYes
user_id does not exist404422 "The user does not exist in the system"No
user-service returns 500500502No
user-service down or timeout-503No

In all four failure cases, nothing is written to db_tasks. That is the invariant of the flow.

8. How to Use It

You must use two terminals and for development we will use the serve service provided by artisan:

# Terminal 1
$ cd user-service
$ php artisan migrate:fresh --seed
$ php artisan serve --port=8000

# Terminal 2
$ cd task-service
$ php artisan migrate:fresh --seed
$ php artisan serve --port=8001

And open http://127.0.0.1:8001/tasks.

Tests with cURL:

# user-service: list
curl -s http://127.0.0.1:8000/api/users

# user-service: user exists -> 200
curl -i http://127.0.0.1:8000/api/users/1

# user-service: does not exist -> 404
curl -i http://127.0.0.1:8000/api/users/999

# task-service: CRUD via API
curl -s -X POST http://127.0.0.1:8001/api/tasks \
  -H "Content-Type: application/json" -H "Accept: application/json" \
  -d '{"title":"End-to-end task","user_id":2}'

curl -s http://127.0.0.1:8001/api/tasks
curl -s http://127.0.0.1:8001/api/tasks/1
curl -s -X PUT http://127.0.0.1:8001/api/tasks/1 \
  -H "Content-Type: application/json" -H "Accept: application/json" \
  -d '{"title":"Renamed","user_id":1}'
curl -s -X DELETE http://127.0.0.1:8001/api/tasks/1

# invalid user -> 422 and NOTHING is saved
curl -s -X POST http://127.0.0.1:8001/api/tasks \
  -H "Content-Type: application/json" -H "Accept: application/json" \
  -d '{"title":"Orphan task","user_id":77}'

# user-service down (Ctrl+C in its terminal) -> 503
curl -s -X POST http://127.0.0.1:8001/api/tasks \
  -H "Content-Type: application/json" -H "Accept: application/json" \
  -d '{"title":"Without user-service","user_id":1}'

Or Postman:

#MethodURLBody (raw / JSON)
1GET{{user_service}}/api/users-
2GET{{user_service}}/api/users/1-
3POST{{task_service}}/api/tasks{"title":"Task","user_id":2}
4GET{{task_service}}/api/tasks-
5PUT{{task_service}}/api/tasks/1{"title":"New","status":"completed"}
6DELETE{{task_service}}/api/tasks/1-
{ "user_service": "http://127.0.0.1:8000", "task_service": "http://127.0.0.1:8001" }

9. Tests

cd user-service && vendor/bin/pest --compact   # 5 tests
cd task-service && vendor/bin/pest --compact   # 23 tests, 68 asserts

None of them spin up the user-service: they use Http::fake() to simulate 200, 404, 500, and dropped connections. The suite is fast and deterministic, but the contract is verified:

Http::fake(['*' => Http::response(['error' => 'User not found'], 404)]);

$this->postJson('/api/tasks', ['title' => 'Task', 'user_id' => 42])->assertStatus(422);

expect(Task::query()->count())->toBe(0);   // nothing was saved

10. The Proof That It Is a Distributed System

Stop the user-service (Ctrl+C) and send a POST /api/tasks. The task-service responds with 503 in milliseconds. No amount of code inside the task-service could prevent it: the information is not in its process, it is in another process, behind another database, across a socket.

In the UI it is seen just as clearly: the /tasks/create form degrades to a numeric input with a banner, and /tasks/{id} continues showing the tasks without the owner's name.

And vice versa: delete user-service/ entirely and the task-service continues to work for listing, editing, and deleting tasks. It only loses the ability to create new tasks. That is the partial availability that real independence between services provides.

11. Limitations of This Design

  • No circuit breaker: each dropped request waits the full 3 s timeout.
  • Double write without distributed transaction: if the user-service returns 200 and then the insert fails, the validation "passed" but there is no task.
  • Contract coupling: if the user-service changes the shape of the 404, the task-service finds out immediately.
  • No authentication: anyone can create tasks. On localhost it doesn't matter.
  • SQLite with concurrent writes: handles the demo, but is not a production engine with multiple workers writing at the same time.

Conclusion and Next Steps in Distributed Architectures

This example demonstrates that even in simple applications, microservices introduce considerable complexity in error management, network latency, and data consistency. As systems grow, asynchronous architectures with queues (such as RabbitMQ), API gateways, centralized authentication, and observability metrics must be incorporated to maintain a robust production environment.

None of this section is implemented. It is a roadmap with the reasoning behind each decision.

Previously we had a microframework for Laravel called Lumen that was ideal for this type of service.

Lumen was Laravel's "lightweight" framework for microservices: fewer dependencies, faster startup. Laravel stopped recommending it for new projects in 2021, and the official documentation states so:

The three reasons why Lumen lost

  1. Laravel caught up in performance. Route caching, OPcache, and middleware management closed the gap. Lumen ended up being "almost as fast" and quite a bit more awkward.
  2. It lacked Sanctum, Passport, Blade, and a decent UI. For a microservice API you ended up manually reinjecting Laravel components, which is Lumen ceasing to be Lumen.
  3. Octane solved the problem Lumen came to solve, but without giving up anything.

Practical consequence for us: the argument "it's a microservice, therefore Lumen" no longer holds up. Speed is bought with Octane, not with a different framework. If you come from a Lumen project, the path is to copy the files to a clean Laravel: Lumen runs on the same illuminate/* components as Laravel.

Authentication and Authorization in a Microservices Architecture

Video thumbnail

In the previous section, we implemented the foundations of our Laravel-based microservices architecture, composed of two independent services: the user service (user-service) and the task management service (task-service).

To evolve the system, the next step consists of incorporating an authentication and authorization mechanism that restricts access to the task module, ensuring that each user exclusively manages their own records.

1. The Centralized Authentication Flow

Previously, the user_id field in the task service was sent directly from the client, which represented a security risk as it was neither protected nor linked to a validated session.

With the new authentication layer, the flow operates as follows:

  1. The user performs the login process by interacting with the task-service interface.
  2. The credential request is forwarded and processed in the user-service, which acts as the central identity authority.
  3. If the credentials are valid, the user-service generates an API token and returns the response with the user data.
  4. The task-service stores this information in the active session, avoiding having to revalidate credentials on every routine read operation.

2. Implementation in the User Service

The user service manages token issuance and credential validation through a dedicated controller:

user-service/app/Http/Controllers/AuthController.php

<?php

namespace App\Http\Controllers;

use App\Models\ApiToken;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    /**
     * Issues an API token based on email + password.
     *
     * POST /api/tokens
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
            'device_name' => ['sometimes', 'string', 'max:100'],
        ]);

        $user = User::query()->where('email', $validated['email'])->first();

        // Same message and same status for "does not exist" and "bad password":
        // otherwise, this response could be used to enumerate which emails are registered.
        if (! $user || ! $user->passwordMatches($validated['password'])) {
            return response()->json([
                'error' => 'Invalid credentials',
            ], 401);
        }

        $issued = ApiToken::issueFor($user, $validated['device_name'] ?? 'api-token');

        return response()->json([
            'token' => $issued['token'],
            'token_type' => 'Bearer',
            'expires_at' => $issued['model']->expires_at?->toIso8601String(),
            'user' => $user,
        ], 201);
    }

    /**
     * Responds with who owns the presented token.
     *
     * GET /api/user
     *
     * This is the endpoint that the task-service queries on each request to
     * know who is calling. It is the equivalent of an identity provider's
     * introspection: the protected resource does not store users, it just
     * forwards the token and asks.
     */
    public function me(Request $request): JsonResponse
    {
        /** @var User $user */
        $user = $request->attributes->get('user');

        return response()->json([
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
        ]);
    }

    /**
     * Revokes the token with which the request was made.
     *
     * DELETE /api/tokens
     */
    public function destroy(Request $request): JsonResponse
    {
        /** @var ApiToken $token */
        $token = $request->attributes->get('api_token');

        $token->delete();

        return response()->json(status: 204);
    }
}

3. Request Protection via Middleware in the Task Service

To guarantee that requests are authorized, the task-service implements a custom middleware that intercepts incoming requests, validating the token against the centralized service before allowing access to the task controllers.

task-service/app/Http/Middleware/AuthenticateWithUserService.php

<?php

namespace App\Http\Middleware;

use App\Services\UserServiceClient;
use App\Support\AuthenticatedUser;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Authenticates the client by asking the user-service.
 *
 * The task-service does not have a users table, so it cannot validate
 * a token on its own: it forwards it to the user-service and asks who
 * it is. This is the equivalent of an identity provider's token introspection.
 *
 * Direct consequence: if the user-service is down, the task-service
 * can no longer authenticate anyone. That coupling is inherent to the
 * "validate via HTTP" design and is the trade-off that avoids a stateless JWT.
 */
class AuthenticateWithUserService
{
    public function __construct(private readonly UserServiceClient $users) {}

    public function handle(Request $request, Closure $next): Response
    {
  
        $token = $request->bearerToken()
            ?? ($request->hasSession() ? $request->session()->get('api_token') : null);

        if (! is_string($token) || $token === '') {
            return $this->reject($request);
        }

        $user = $this->users->authenticate($token);

        if ($user === null) {
            // Expired or revoked token: the web session is no longer valid either.
            // Note: /api/* routes do not start a session, so we must
            // check before touching it.
            if ($request->hasSession()) {
                $request->session()->forget('api_token');
            }

            return $this->reject($request);
        }

        $request->attributes->set('authenticated_user', AuthenticatedUser::fromArray($user));

        return $next($request);
    }

    private function reject(Request $request): Response
    {
        if ($request->is('api/*') || $request->expectsJson()) {
            return response()->json([
                'error' => 'Unauthenticated.',
                'message' => 'Send a valid token like: Authorization: Bearer <token>',
            ], 401);
        }

        return redirect()->guest(route('login'));
    }
}

4. Rest of the Task Module

The rest of the task module is practically the same, since we have the middleware running on each request:

task-service/bootstrap/app.php

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'auth.user-service' => AuthenticateWithUserService::class,
    ]);
})

It is not necessary to take the request from the controller to validate the user; we send it directly from the data we keep in the session:

task-service/app/Http/Controllers/TaskController.php

class TaskController extends Controller
{
    ***
    public function store(StoreTaskRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        Task::query()->create([
            'title' => $validated['title'],
            'user_id' => $this->user()->id,
            'status' => $validated['status'] ?? Task::STATUS_PENDING,
        ]);

        return redirect()
            ->route('tasks.index')
            ->with('success', 'Task created successfully.');
    }
}              

5. Scalability Considerations and Challenges in Microservices

As a distributed system grows, handling authentication through constant synchronous calls can introduce latency. While the use of encrypted tokens (such as JWT) allows identities to be verified in a decentralized manner without querying an external database on every request, architectural complexity remains a critical factor.

Likewise, when the application requires replicating authentication modules or shared views across multiple microservices, the recommended strategy is not code duplication, but extracting those components into private packages via Composer. Currently, since it is ONLY a service and a demo app, we have this controller which is ONLY AN INTERFACE (since the verification, generation, deletion process, and overall control continue to be maintained by the user service):

task-service/app/Http/Controllers/AuthController.php

Which passes the data directly to the user service:

$token = $users->issueToken($credentials + ['device_name' => 'task-service-web']);

Implementing microservices brings flexibility and technological independence, but introduces considerable operational overhead in network management, state sharing, and security. It is essential to evaluate whether the complexity of a distributed architecture is fully justified compared to the advantages of a well-structured modular monolith.

Rate Limiting and Brute Force Protection

Video thumbnail

To reinforce security in a microservices architecture, implementing rate limiting mechanisms (or throttling) is essential, especially on critical endpoints such as the authentication module where access credentials are processed.

1. Request Limiter Configuration

Laravel allows you to define custom limiters within the main service provider (AppServiceProvider). To protect the login access point against brute-force attacks, two complementary counters are configured to act simultaneously:

  • IP-based Limit: Stops massive sweeps where an attacker attempts to test multiple accounts from the same network address.
  • Account-based Limit: Stops targeted attacks directed against a specific email address using multiple IP addresses.

The framework evaluates all defined limits and applies the strictest one; as soon as one of them is exhausted, the resulting HTTP response is the 429 Too Many Requests code.

2. Implementing the Rate Limiter in Code

Below is the limiter configuration using the RateLimiter class and hash encryption to protect cached data privacy:

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->registerLoginRateLimiter();
    }

    private function registerLoginRateLimiter(): void
    {
        RateLimiter::for('login', function (Request $request): array {
            $decay = (int) config('tokens.throttle.decay_seconds');
            $email = mb_strtolower((string) $request->input('email'));

            return [
                // Limit based on the client's IP address
                Limit::perMinute((int) config('tokens.throttle.per_ip'))
                    ->by('ip:'.$request->ip()),

                // Limit based on email and IP combined using a hash
                Limit::perMinute((int) config('tokens.throttle.per_account'))
                    ->by('email:'.hash('sha256', $email).'|ip:'.$request->ip()),
            ];
        });
    }
}

3. Configuration File and Route Assignment

Threshold and wait time parameters (decay time) are managed via centralized configuration variables:

config/tokens.php

'throttle' => [
    'per_account' => (int) env('LOGIN_THROTTLE_PER_ACCOUNT', 5),
    'per_ip' => (int) env('LOGIN_THROTTLE_PER_IP', 20),
    'decay_seconds' => (int) env('LOGIN_THROTTLE_DECAY', 60),
];

Finally, the limiter is assigned as middleware directly to the route responsible for issuing authentication tokens:

routes/api.php

Route::post('/tokens', [AuthController::class, 'store'])->middleware('throttle:login');

Incorporating strict rate-limiting policies effectively mitigates the risks associated with automated credential guessing attacks. By storing failed attempt records using secure hashes in the cache system, data integrity is protected without compromising the overall performance of the microservices.

Observability and Traceability in Microservices

Video thumbnail

As the complexity of a microservices architecture increases, tracking events and errors across multiple independent applications becomes a critical necessity. When executing requests that involve chained HTTP calls (such as the interaction between the task service and the user service), traditional exception handling mechanisms prove insufficient to determine the exact origin of an error or the experience of a specific client.

1. The Correlation ID Concept (X-Request-Id)

To achieve full traceability, the correlation identifier pattern or Correlation ID is implemented. It consists of associating a unique identifier (UUID) to each incoming request. If the request already includes an X-Request-Id header, the system preserves and propagates it; otherwise, it automatically generates one at the entry boundary and injects it into both the internal request cycle and outbound calls to other microservices.

2. Injection and Log Context Middlewares

The strategy relies on two main middlewares registered in the global API group within the system configuration (bootstrap/app.php) of BOTH microservices:

  • EnsureRequestId: Guarantees that every request possesses a unique identifier, assigning it to the $request object and returning it in the HTTP response header.
  • AttachLogContext: Captures the request_id and defines a structured global context for Laravel's logging system.

EnsureRequestId.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class EnsureRequestId
{
    public function handle(Request $request, Closure $next): Response
    {
        $requestId = $request->header('X-Request-Id');

        if (! is_string($requestId) || $requestId === '') {
            $requestId = (string) Str::uuid();
        }

        $request->attributes->set('request_id', $requestId);

        /** @var Response $response */
        $response = $next($request);

        $response->headers->set('X-Request-Id', $requestId);

        return $response;
    }
}

Using the Log::withContext() method allows attaching contextual data (service, IP address, HTTP method, path, and request_id) to all logs generated during request execution in a completely automated way:

AttachLogContext.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class AttachLogContext
{
    public function handle(Request $request, Closure $next): Response
    {
        $requestId = $request->attributes->get('request_id');

        if (! is_string($requestId) || $requestId === '') {
            $requestId = $request->header('X-Request-Id');
        }

        if (! is_string($requestId) || $requestId === '') {
            $requestId = null;
        }

        Log::withContext([
            'request_id' => $requestId,
            'service' => config('app.name'),
            'ip' => $request->ip(),
            'method' => $request->getMethod(),
            'path' => $request->path(),
        ]);

        return $next($request);
    }
}

3. Header Propagation in the HTTP Client

To prevent traceability from breaking when jumping from one microservice to another, the service client (UserServiceClient) handles attaching the X-Request-Id header to every outgoing request (GET, POST, or DELETE requests):

task-service/app/Services/UserServiceClient.php

private function traceHeaders(): array
{
    $headers = [];

    if (function_exists('request')) {
        $req = request();
        if (! $req) {
            return $headers;
        }

        $requestId = null;

        if ($req->hasHeader('X-Request-Id')) {
            $requestId = $req->header('X-Request-Id');
        } elseif ($req->attributes && $req->attributes->has('request_id')) {
            $requestId = $req->attributes->get('request_id');
        }

        if (is_string($requestId) && $requestId !== '') {
            $headers['X-Request-Id'] = $requestId;
        }
    }

    return $headers;
}

4. Event Logging and Health Check

With this structure, controllers can focus solely on emitting informative or warning messages without worrying about attaching manual request data:

// Log example in TaskController
Log::info('The user created a task');

Additionally, an endpoint can be incorporated to verify the operational availability of the service quickly via a health check controller (Health Check):

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;

class HealthController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json([
            'status' => 'ok',
            'service' => config('app.name', 'user-service'),
            'timestamp' => now()->toIso8601String(),
        ]);
    }
}

The inclusion of correlation identifiers and automatic context injection into log files transform scattered events into a continuous history of traceable data. This allows tracking the path of a request across multiple microservices, optimizing error diagnosis and improving the overall observability of the architecture.

Modularization and Code Reuse with Local Composer Packages

Video thumbnail

When developing a microservices architecture with PHP and Laravel, the need frequently arises to share cross-cutting components among multiple applications (such as tracing middlewares, health controllers, or authentication clients). Maintaining duplicate copies of this code in each project leads to silent divergences and operational risks when specifications change.

To solve this problem cleanly within a monorepo, the optimal strategy consists of extracting common code into local packages managed by Composer using path type repositories.

In the previous observability section, two middlewares were added to both services. The result was this:

user-service/app/Http/Middleware/EnsureRequestId.php     (18 lines)
user-service/app/Http/Middleware/AttachLogContext.php    (32 lines)
task-service/app/Http/Middleware/EnsureRequestId.php     (18 lines)  <- identical
task-service/app/Http/Middleware/AttachLogContext.php    (32 lines)  <- identical

Four files where two were enough. And the real problem is not the size:

The real problem is divergence. If tomorrow the request_id format needs to change, you have to remember to change it in two places. If it's changed in one and not the other, the task-service generates IDs with one format and the user-service with another. And the symptom appears in production, on a Tuesday, with no test detecting it.
demo-microservicios/
├── packages/
│   ├── microservices-observability/
│   │   ├── composer.json
│   │   ├── README.md
│   │   └── src/
│   │       ├── MicroservicesObservabilityServiceProvider.php
│   │       └── Http/
│   │           ├── Controllers/
│   │           │   └── HealthController.php
│   │           └── Middleware/
│   │               ├── AttachLogContext.php
│   │               └── EnsureRequestId.php
│   │
│   └── microservices-user-service-client/
│       ├── composer.json
│       ├── README.md
│       ├── config/
│       │   └── user-service-client.php
│       └── src/
│           ├── UserServiceClientServiceProvider.php
│           ├── UserServiceClient.php
│           ├── AuthenticatedUser.php
│           ├── TokenSession.php
│           ├── Contracts/
│           ├── Exceptions/
│           └── Http/Middleware/
│               └── AuthenticateWithUserService.php
│
├── user-service/
│   ├── composer.json      <- + repositories, + require
│   └── app/
│       └── Http/Middleware/
│           └── AuthenticateApiToken.php    (remains: service specific)
│
└── task-service/
    ├── composer.json      <- + repositories, + require
    └── app/
        └── Http/Middleware/
            └── AuthenticateWithUserService.php    (remains: service specific)

1. Initialization and Structure of the Local Package

To create a new PHP package from scratch, the first step consists of initializing its configuration via Composer inside the dedicated directory (for example, packages/microservices-observability/):

$ composer init

And there are several additional commands, for example, you can add Laravel dependencies with Composer:

$ composer require "illuminate/support:^13.0" "illuminate/http:^13.0"

To configure Autoload (PSR-4) and Autodiscovery (extra): Since Composer does not have a specific console command to modify the autoload or extra sections, you must open the newly created composer.json file with your code editor (like VS Code) and manually paste these two blocks inside the main object:json

"autoload": {
   "psr-4": {
        "Demo\\Microservices\\Observability\\": "src/"
   }
},
"extra": {
   "laravel": {
        "providers": [
             "Demo\\Microservices\\Observability\\MicroservicesObservabilityServiceProvider"
        ]
   }
},
"prefer-stable": true

To apply Autoload changes: Whenever you modify the autoload section, run this command so that Composer registers your folder paths:bash

$ composer dump-autoload

The interactive composer init command generates the main composer.json file, where metadata, dependencies, and the autoload engine mapping (PSR-4) are defined:

{
  "name": "demo/microservices-observability",
  "description": "Correlation ID + log context for Laravel microservices",
  "type": "library",
  "license": "MIT",
  "require": {
    "php": "^8.2",
    "illuminate/support": "^13.0",
    "illuminate/http": "^13.0",
    "illuminate/routing": "^13.0"
  },
  "autoload": {
    "psr-4": {
      "Demo\\Microservices\\Observability\\": "src/"
    }
  },
  "extra": {
    "laravel": {
      "providers": [
        "Demo\\Microservices\\Observability\\MicroservicesObservabilityServiceProvider"
      ]
    }
  },
  "minimum-stability": "dev",
  "prefer-stable": true
}
  • name: Unique identifier of the package (for example, demo/microservices-observability), used by Composer to resolve dependencies.
  • description: Brief textual description about the purpose and functionality of the component.
  • type: Configured as library to distinguish a reusable code package from a final executable project.
  • license: Defines the distribution license of the package, usually set to MIT.
  • keywords: List of associated keywords to facilitate categorization and identification of the package.
  • require: Declares strict dependencies necessary for its operation (such as illuminate/* components) without forcing the installation of the full framework.
  • autoload.psr-4: Defines the namespace of the package and the root directory src/ where PHP maps and locates classes automatically.
  • extra.laravel.providers: Specifies the main ServiceProvider so that Laravel discovers and loads the package automatically without needing to register it manually.
  • minimum-stability: Configured as dev to allow Composer to accept and resolve local packages that do not have formal version tags.
  • prefer-stable: Configured to true to prioritize stable versions in the rest of the system dependencies even if development branches are allowed.

2. The Service Provider and Automatic Discovery

Laravel packages use a provider class (ServiceProvider) to register their bindings in the dependency container or publish middleware aliases. Thanks to the extra.laravel.providers block in composer.json, Laravel automatically detects and loads the package without requiring manual registration.

namespace Demo\Microservices\Observability;

use Demo\Microservices\Observability\Http\Middleware\AttachLogContext;
use Demo\Microservices\Observability\Http\Middleware\EnsureRequestId;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;

class MicroservicesObservabilityServiceProvider extends ServiceProvider
{
    public const ALIAS_REQUEST_ID = 'request.id';
    public const ALIAS_LOG_CONTEXT = 'log.context';

    public function boot(Router $router): void
    {
        $router->aliasMiddleware(self::ALIAS_REQUEST_ID, EnsureRequestId::class);
        $router->aliasMiddleware(self::ALIAS_LOG_CONTEXT, AttachLogContext::class);
    }
}

3. Linking the Local Package in Consumer Applications

To consume the package without publishing it to a remote repository like Packagist, the repositories section of type path is added to the composer.json of each microservice (such as task-service or user-service):

"repositories": [
  {
    "type": "path",
    "url": "../packages/microservices-observability"
  }
],
"require": {
  "php": "^8.3",
  "laravel/framework": "^13.0",
  "demo/microservices-observability": "@dev"
}

When running the update command in the client application, Composer creates a symbolic link (symlink) in the vendor/ folder pointing to the package directory, allowing any change in the package's source code to be reflected instantly without reinstalling:

$ composer update demo/microservices-observability

4. Publishing Configuration Files

When a package includes user-customizable options (such as authentication routes or timeouts), the ServiceProvider exposes the file via the publishes() method:

public function boot(Router $router): void
{
    if ($this->app->runningInConsole()) {
        $this->publishes([
            __DIR__.'/../config/user-service-client.php' => config_path('user-service-client.php'),
        ], 'user-service-client-config');
    }
}

To copy said configuration file to the main application's config/ directory, run the following Artisan command:

$ php artisan vendor:publish --tag=user-service-client-config

5. Step-by-Step Migration

The seven steps that were executed, just in case it needs to be repeated with another module:

  1. Create the package skeleton: packages/<name>/ with composer.json, README.md, and src/.
  2. Copy the code from app/ to src/ (copy, do not move yet).
  3. Change the namespace from App\Http\Middleware to Demo\Microservices\Observability\Http\Middleware.
  4. Create the ServiceProvider and declare it in extra.laravel.providers.
  5. Add repositories and require to each application's composer.json.
  6. Run composer update demo/microservices-observability in each service.
  7. Update imports in bootstrap/app.php, delete old files from app/Http/Middleware/ and verify with pint and pest.

Extracting shared code into local packages via path repositories consolidates a clean, modular, and maintainable microservices architecture. This allows multiple services to consume identical contracts and implementations, eliminating file duplication and streamlining system updates.

Integration of a Third Microservice: The Billing Service

Video thumbnail

To simulate a real production environment within our distributed architecture, the next step consists of incorporating a third independent service called Billing Service. Just like the task module, this component requires prior authentication to protect its resources and manage commercial operations.

1. Application Independence and Session Isolation

With the addition of this new application, the system features multiple completely independent frontend services: the task service and the billing service. Each operates as an autonomous application maintaining its own database, business logic, and session management.

Due to this architectural separation, cookies and session states are not shared by default among the different applications. Although both modules implement the same protection mechanism via middleware, when navigating to the billing section after having logged into the task module, the system independently demands a new authentication.

2. Authentication Challenges in Distributed Environments

In the local development environment, the simultaneous execution of services via commands like php artisan serve distributes each application across different ports or domains, accentuating session isolation. In a production environment, this behavior can be managed by configuring a primary domain with shared subdomains.

However, from the perspective of user experience, the ideal is for the platform to behave as a unified system, preventing the user from having to log in repeatedly every time they interact with a different microservice.

The distribution of responsibilities across independent microservices introduces complex challenges in identity and session management. To resolve this fragmentation and ensure a unified access experience, the next step in the architecture's evolution consists of implementing a centralized authentication server.

SSO in Microservices: A Single Login with a Dedicated Identity Provider

Video thumbnail

Earlier we added a third microservice very similar to the tasks one: the typical CRUD of anything, previously it was tasks and now it is invoices. It is an authenticated module, and the problem appears again here: resources are shared and login was handled in the task service, which is a problem; what we had done was repeat the login in the invoice one. Neither authenticating in two different pages nor, above all, implementing two authentication screens makes sense: the experience needs to feel like a single application.

For that we are going to build what is known as SSO, single sign-on, supported by an IdP, identity provider. Remember these terms, because we will use them all the time: SSO, IdP, and RP, relying party. Our RPs are task-service and billing-service: the two services that rely on the IdP to know who the user is.

It is a dense topic. I recommend downloading the application, the v0.5 tag, and doing some tests to see how it works; even so, I will do my best to make it understood with what is discussed here. What we are trying to do is place the session in a single place, and with what we have seen so far you can already guess the goal.

The mechanism is a simplified version of the OAuth 2.0 Authorization Code flow. The main difference is that here the client is internal and the IdP is custom-made, so state, nonce, and PKCE are omitted.

Browser                     task-service (RP)         user-service (IdP)
    |                             |                            |
    | GET /tasks (no session)     |                            |
    |---------------------------->| middleware auth.user-service |
    | 302 /sso/start              |                            |
    |<----------------------------|                            |
    | GET /sso/start              |                            |
    |---------------------------->| SsoStartController         |
    | 302 /authorize?client=task&redirect_uri=...              |
    |<----------------------------|                            |
    | GET /authorize...           |                            |
    |--------------------------------------------------------->|
    |                             |        SSO session?        |
    |                             |        NO -> 302 /login    |
    | 302 /login?client=task&redirect_uri=...                    |
    |<---------------------------------------------------------|
    | GET /login (form)           |                            |
    |--------------------------------------------------------->|
    | POST /login (email+pass)    |                            |
    |--------------------------------------------------------->| Auth::attempt
    |                             |                            | issues code (60 s)
    | 302 redirect_uri?code=XYZ   |                            |
    |<---------------------------------------------------------|
    | GET /sso/callback?code=XYZ                               |
    |---------------------------->| SsoCallbackController      |
    |                             | POST /api/sso/exchange     |
    |                             |--------------------------->| validates code + client
    |                             |                            | creates RP token
    |                             |<---------------------------| 201 {token, user}
    |                             | loginWithToken() -> session|
    | 302 /tasks                  |                            |
    |<----------------------------|                            |

The Session Has to Live in a Single Place

The problem is that they are different applications: a session lives inside a single application and cannot be shared between them. That reason is what forces us to change several things. We had a single service, the user-service, which simply validated tokens; user data, for example that an email is valid, has always lived there. But the login part was duplicated: there was a login in task-service and another in billing-service, a mess that in a real application, where services will be many more, is unsustainable. Now the login route, the one that validates email and password, lives in the user-service, which becomes our IdP.

Regarding ports: I start user-service first with php artisan serve, which being the first ends up on 8000; next I start the tasks and billing ones, in that order, and they end up on 8001 and 8002. This is the part of the IdP routes that matters to us:

user-service/routes/web.php

Route::get('/', function () {
    if (auth()->check()) {
        return view('welcome');
    }

    return redirect()->route('login');
})->name('home');

Route::get('/login', [WebLoginController::class, 'show'])->name('login')->middleware('guest');
Route::post('/login', [WebLoginController::class, 'login'])->middleware('throttle:6,1');
Route::get('/logout', [WebLoginController::class, 'logout'])->name('logout');
Route::post('/logout', [WebLoginController::class, 'logout']);

Route::get('/authorize', [SsoController::class, 'authorize'])->name('sso.authorize');

user-service/routes/api.php

Route::post('/tokens', [AuthController::class, 'store'])->middleware('throttle:login');
Route::post('/sso/exchange', [SsoController::class, 'exchange']);

Route::middleware('auth.api-token')->group(function () {
    Route::get('/user', [AuthController::class, 'me']);
    Route::delete('/tokens', [AuthController::class, 'destroy']);
});

The Problem, Live

If I try to enter 127.0.0.1:8002/facturas without being authenticated, it sends me to authentication and, look at the address bar, a return URL with the flow parameters appears. If I do the same with the tasks application, on 8001, the same thing happens: it asks me for authentication. At this point I authenticate only once, with the seeder's test email and password, and I log in; from there I can also navigate to billing, because by being authenticated in a single place both modules work correctly and the rest of the operations go well.

Another detail for later: from the root of each application I go straight to the module we care about, the tasks root redirects to /tasks and billing's to /facturas.

Three Controllers That Live in the Package

Here some strange classes appear that we are going to analyze, and all of them live in our package, demo/microservices-user-service-client: SsoStartController, which as its name suggests is where it starts; SsoCallbackController, the return; and SsoLogoutController. I am going to start with logout, because its logic is the easiest to follow, and the others are a little bit more tangled.

First, the package configuration, because the values that these controllers will read come from there:

packages/microservices-user-service-client/config/user-service-client.php

return [
    'url' => env('USER_SERVICE_URL', 'http://127.0.0.1:8000'),

    'timeout' => (int) env('USER_SERVICE_TIMEOUT', 3),

    // SSO Client: name of this application to the IdP.
    // In task-service USER_SERVICE_CLIENT=task is defined and in
    // billing-service, USER_SERVICE_CLIENT=billing.
    'client' => env('USER_SERVICE_CLIENT', 'app'),

    // RP callback URL. If null, url('/sso/callback') is used.
    'callback_url' => env('USER_SERVICE_CALLBACK_URL'),

    // Route with which the SSO flow starts.
    'sso_start_route' => env('USER_SERVICE_SSO_START_ROUTE', 'sso.start'),
];

url is the URL of the authentication service, the user-service, and since it is the first one I start it always ends up on 8000. timeout is what is expected when making the request to that service before giving up. client is more or less irrelevant here: it is the name of this application to the IdP. callback_url, by default, is url('/sso/callback'); you can also define it, but so you know what it would be: the route we register next. And sso_start_route is the name of the route with which the whole process starts. In billing and task it is exactly the same, because both consume the same package.

task-service/routes/web.php

Route::redirect('/', '/tasks');

Route::get('/sso/start', SsoStartController::class)->name('sso.start');
Route::get('/sso/callback', SsoCallbackController::class)->name('sso.callback');
Route::post('/logout', SsoLogoutController::class)->name('logout');

Route::middleware('auth.user-service')->group(function () {
    Route::resource('tasks', TaskController::class);
});

The three package controllers are single-action, with __invoke; remember that you can place a controller with named methods if you prefer. In billing the routes are identical, with facturas instead of tasks.

Logout: Close Session and Revoke Token

Let's start with logout. The controller gets the user-service URL from the configuration, destroys the local session, and redirects to the IdP's /logout with a redirect_uri to return:

packages/microservices-user-service-client/src/Http/Controllers/SsoLogoutController.php

class SsoLogoutController extends Controller
{
    public function __invoke(Request $request, TokenSession $session): RedirectResponse
    {
        $base = rtrim((string) config('user-service-client.url'), '/');
        $session->logout($request);

        return redirect()->away($base.'/logout?'.http_build_query([
            'redirect_uri' => url('/'),
        ]));
    }
}

Look at TokenSession: it also lives in the package, and is simply a service that manages the token lifecycle in the session. Its logout is the useful part: before destroying the local session, it revokes the token by calling the IdP. If we only deleted it from the session, the token would still be alive in the user-service table; this way it is truly rendered unusable.

// packages/microservices-user-service-client/src/TokenSession.php
public const SESSION_KEY = 'api_token';

public function loginWithToken(Request $request, string $token): void
{
    $request->session()->regenerate();
    $request->session()->put(self::SESSION_KEY, $token);
}

public function logout(Request $request): void
{
    $token = $request->session()->get(self::SESSION_KEY);

    if (is_string($token) && $token !== '') {
        try {
            $this->users->revokeToken($token);
        } catch (Throwable) {
            // The local session is destroyed anyway: revoking is best
            // effort, not a condition to log out. If the peer is
            // down, the token remains orphaned and expires on its own.
        }
    }

    // invalidate() empties the session and generates a new id; regenerateToken()
    // restores the CSRF token, which the emptying swept away.
    $request->session()->invalidate();
    $request->session()->regenerateToken();
}

And on the other side, the IdP destroys its own session, which is the one shared by all services:

user-service/app/Http/Controllers/WebLoginController.php

public function logout(Request $request): RedirectResponse
{
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();

    $redirectUri = $request->query('redirect_uri');

    if (is_string($redirectUri) && $redirectUri !== '') {
        return redirect()->away($redirectUri);
    } /* ... */
}

Since we are importing this controller in each application, logout is handled internally and becomes available in task and billing without duplicating a line. Upon finishing, the user returns to the application via the redirect_uri and, if they try to enter again, the SSO flow sends them to login.

SsoStartController: The Flow Start

Let's go now with SsoStartController. It gets the configured client name, the IdP base, and the callback URL; it builds the /authorize URL and redirects towards the IdP:

packages/microservices-user-service-client/src/Http/Controllers/SsoStartController.php

class SsoStartController extends Controller
{
    public function __invoke(Request $request): RedirectResponse
    {
        $client = (string) config('user-service-client.client');
        $base = rtrim((string) config('user-service-client.url'), '/');
        $callback = config('user-service-client.callback_url');

        if (! is_string($callback) || $callback === '') {
            $callback = url('/sso/callback');
        }

        $authorize = $base.'/authorize?'.http_build_query([
            'client' => $client,
            'redirect_uri' => $callback,
        ]);

        return redirect()->away($authorize);
    }
}

The validation of "if it is not defined, we take this route" for the callback is what you see in the if: it can be relaxed by always leaving the same one defined for everyone. When this request reaches the IdP, it is precisely the request to /authorize that we registered in its routes.

The Middleware That Queries the IdP

In the protected routes of task and billing, a middleware appears which in the route is written as an alias, auth.user-service. That alias is registered in the package's service provider and points to the package class; you can also reference the class directly if you prefer, but the alias is a more elegant way to define it:

packages/microservices-user-service-client/src/UserServiceClientServiceProvider.php

public const ALIAS_AUTHENTICATE = 'auth.user-service';

public function boot(Router $router): void
{
    if (! array_key_exists(self::ALIAS_AUTHENTICATE, $router->getMiddleware())) {
        $router->aliasMiddleware(self::ALIAS_AUTHENTICATE, AuthenticateWithUserService::class);
    } /* ... */
}

The middleware takes the token, which can come from the Authorization: Bearer header when consumed via API, or from the RP session when browsing the web. If there is no token, or the IdP says it is no longer valid, it rejects: a 401 on the API and, on the web, a redirection to the start of the SSO flow:

packages/microservices-user-service-client/src/Http/Middleware/AuthenticateWithUserService.php

public function handle(Request $request, Closure $next): Response
{
    $token = $request->bearerToken()
        ?? ($request->hasSession() ? $request->session()->get(TokenSession::SESSION_KEY) : null);

    if (! is_string($token) || $token === '') {
        return $this->reject($request);
    }

    $user = $this->users->authenticate($token);

    if ($user === null) {
        // Expired or revoked token: the web session is no longer useful either.
        if ($request->hasSession()) {
            $request->session()->forget(TokenSession::SESSION_KEY);
        }

        return $this->reject($request);
    }

    $request->attributes->set(
        AuthenticatedUser::ATTRIBUTE,
        AuthenticatedUser::fromArray($user),
    );

    return $next($request);
}

private function reject(Request $request): Response
{
    if ($request->is('api/*') || $request->expectsJson()) {
        return new JsonResponse(['error' => 'Unauthenticated.'], 401);
    }

    $startRoute = config('user-service-client.sso_start_route');

    if (! is_string($startRoute) || $startRoute === '') {
        return new JsonResponse(['error' => 'Unauthenticated.'], 401);
    }

    return $this->redirector->guest($this->url->route($startRoute));
}

This is the classic mechanism of "you can enter this route if you are authenticated": if the user does not have a session, it is this reject that sends them to sso.start, the start of the flow we have been following. Furthermore, since the RP application has no users table, it cannot validate the token on its own: with authenticate($token) it forwards it to the user-service, which answers back who the user is. This happens on every request, not just when logging in, and it is what allows the route to proceed with $next when everything goes well.

The IdP: /authorize

When SsoStartController redirects, the request lands in the base application, the user-service: /authorize. There, if there is no session, it redirects to login carrying client and redirect_uri; if there is one, it issues the code:

user-service/app/Http/Controllers/SsoController.php

public function authorize(Request $request, SsoTicketIssuer $issuer): RedirectResponse|View
{
    if (! Auth::check()) {
        return redirect()->route('login', $request->only(['client', 'redirect_uri']));
    }

    $validated = $request->validate([
        'client' => ['required', 'string'],
        'redirect_uri' => ['required', 'string'],
    ]);

    $user = $request->user();
    $code = $issuer->issue($user, $validated['client'], $validated['redirect_uri']);

    $separator = str_contains($validated['redirect_uri'], '?') ? '&' : '?';

    Log::info('idp.sso.authorized', [
        'user_id' => $user->id,
        'client' => $validated['client'],
        'request_id' => $request->attributes->get('request_id'),
    ]);

    return redirect()->away($validated['redirect_uri'].$separator.'code='.urlencode($code));
}

That Auth::check() counts as a session of the IdP's own web guard, the one we were interested in in the previous video. The login that creates it is this:

user-service/app/Http/Controllers/WebLoginController.php

public function login(Request $request, SsoTicketIssuer $issuer): RedirectResponse
{
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required', 'string'],
        'client' => ['nullable', 'string'],
        'redirect_uri' => ['nullable', 'string'],
    ]);

    if (! Auth::attempt(['email' => $credentials['email'], 'password' => $credentials['password']], true)) {
        return back()->withErrors(['email' => 'Invalid credentials.'])
            ->withInput($request->only('email', 'client', 'redirect_uri'));
    }

    $request->session()->regenerate();

    $client = $credentials['client'] ?? null;
    $redirectUri = $credentials['redirect_uri'] ?? null;

    if (is_string($client) && $client !== '' && is_string($redirectUri) && $redirectUri !== '') {
        $code = $issuer->issue(Auth::user(), $client, $redirectUri);

        $separator = str_contains($redirectUri, '?') ? '&' : '?';

        return redirect()->away($redirectUri.$separator.'code='.urlencode($code));
    }

    return redirect()->intended(route('home'));
}

Look at the detail at the end: if the form arrived with client and redirect_uri, which is what hangs on the login screen when the SSO flow sent you there, the login itself issues the code and returns you to the RP callback with ?code=.... The IdP session has already been created, and that is the point that makes everything else work.

The SSO Code: Whitelist, Hash, and TTL

The code is generated precisely in the authorization part, in SsoTicketIssuer::issue, which is the method to which authorize and login pass the client and the redirect URL. First, the configuration of allowed clients: the IdP whitelist:

user-service/config/sso.php

'clients' => [
    'task' => [
        'http://127.0.0.1:8001/sso/callback',
        'http://localhost:8001/sso/callback',
    ],
    'billing' => [
        'http://127.0.0.1:8002/sso/callback',
        'http://localhost:8002/sso/callback',
    ],
],

'ticket_ttl' => (int) env('SSO_TICKET_TTL', 60),

and then the issuer:

user-service/app/Services/SsoTicketIssuer.php

public function issue(User $user, string $client, string $redirectUri): string
{
    $clients = config('sso.clients', []);

    if (! is_array($clients) || ! array_key_exists($client, $clients)) {
        throw new HttpException(400, 'Unauthorized SSO client.');
    }

    $allowed = $clients[$client];

    if (is_string($allowed)) {
        $allowed = [$allowed];
    }

    if (! is_array($allowed) || ! in_array($redirectUri, $allowed, true)) {
        throw new HttpException(400, 'redirect_uri not authorized for this client.');
    }

    // A single active ticket per user and client: if there is one before, we delete it.
    SsoTicket::query()
        ->where('user_id', $user->id)
        ->where('client', $client)
        ->whereNull('used_at')
        ->where('expires_at', '>', now())
        ->delete();

    $code = Str::random(64);

    SsoTicket::query()->create([
        'code_hash' => hash('sha256', $code),
        'user_id' => $user->id,
        'client' => $client,
        'expires_at' => now()->addSeconds((int) config('sso.ticket_ttl', 60)),
        'used_at' => null,
    ]);

    return $code;
}

Only whitelist clients are allowed and, for each one, an exact redirect_uri. Then any previous unused ticket is deleted, a random code is generated, and the sha256 hash is saved with its expiration. For security, the plain-text code is never in the database: only the hash. The real code lives an instant, in the redirect URL, and returns to the RP, which is precisely the callback of $redirect_uri. The Log::info you saw in authorize keeps the traceability of request_id, the previous one, to be able to trace this request between services.

The RP Callback: Exchanging the Code for the Token

The IdP redirection brings the code back to the RP application, to SsoCallbackController. It looks up the code, exchanges it for a token, and leaves it in the session:

packages/microservices-user-service-client/src/Http/Controllers/SsoCallbackController.php

class SsoCallbackController extends Controller
{
    public function __invoke(
        Request $request,
        IdentityProvider $users,
        TokenSession $session,
    ): RedirectResponse {
        $code = $request->query('code');
        $client = (string) config('user-service-client.client');

        if (! is_string($code) || $code === '') {
            abort(401, 'Missing SSO code.');
        }

        $result = $users->exchangeCode($code, $client);

        if (! is_array($result)) {
            abort(401, 'Could not complete login.');
        }

        $session->loginWithToken($request, $result['token']);

        return redirect()->intended('/');
    }
}

If the callback entry does not bring a code, which is the authentication factor of the flow, it aborts with a 401. If it brings one, it calls exchangeCode, the method of the IdentityProvider contract that the package executes against the IdP via HTTP, server to server: the code travels in clear text a single time and the IdP is the one that turns it into a hash to look it up in its table. If the exchange returns no results, due to an invalid, expired, or other client's code, it aborts likewise. With the token in hand, loginWithToken saves it in the RP session, under the api_token key, and redirects to the root, which you remember points to each application's module. The token stays in the session, not its hash.

The Exchange: /api/sso/exchange

The exchange is resolved on the IdP side, in SsoController::exchange,

user-service/app/Http/Controllers/SsoController.php

public function exchange(Request $request): JsonResponse
{
    $validated = $request->validate([
        'code' => ['required', 'string'],
        'client' => ['required', 'string'],
    ]);

    $ticket = SsoTicket::query()
        ->with('user')
        ->where('code_hash', hash('sha256', $validated['code']))
        ->first();

    if (! $ticket || ! $ticket->isValid()) {
        return response()->json(['error' => 'Invalid or expired SSO code.'], 400);
    }

    if ($ticket->client !== $validated['client']) {
        return response()->json(['error' => 'Invalid SSO code client.'], 400);
    }

    $deviceName = $ticket->client.'-sso';

    $issued = ApiToken::issueFor(
        $ticket->user,
        $deviceName,
        now()->addMinutes((int) config('tokens.ttl_minutes')),
    );

    $ticket->update(['used_at' => now()]);

    return response()->json([
        'token' => $issued['token'],
        'token_type' => 'Bearer',
        'expires_at' => $issued['model']->expires_at?->toIso8601String(),
        'user' => [
            'id' => $ticket->user->id,
            'name' => $ticket->user->name,
            'email' => $ticket->user->email,
            'created_at' => $ticket->user->created_at?->toIso8601String(),
            'updated_at' => $ticket->user->updated_at?->toIso8601String(),
        ],
    ], 201);
}

The IdP hashes the received code, looks up the ticket whose hash matches, and validates that it is neither expired nor used and that the client redeeming it is the client for which it was issued. Then it issues a new ApiToken, with a device_name of type task-sso or billing-sso, marks the ticket as used, so that the code is single-use, and returns the token along with user data. That token is no longer the code: it is the one the RP stores in its session and the one its middleware will verify against the IdP on each subsequent request. Regarding token handling, it is the same as for passwords: it is stored hashed, but verification always belongs to the user-service, because it is not enough for the IdP session to be active. It resembles a JWT in idea, but here it is an opaque token queried via HTTP on each request: if it was revoked, access is not allowed; if it goes well, it simply proceeds.

Why Was Billing Already Authenticated?

An important detail to finish: the billing service works automatically when we have already authenticated in the tasks one. The reason is the IdP session and its Auth::check(), which is true. When starting the session from task, the user-service web guard ended up with the user session; that session lives in the browser, as an IdP cookie, and that is why it is shared by all services, although each one only uses it through the IdP. When the flow starts from billing, it arrives at /authorize again, and that is where the if we already analyzed falls: if there is no session, to login; if there is one, as is our case, it does not go through login, it issues a new code, this time for the billing client, with its traceability, and redirects to the callback with it. If you missed that part, go back to the IdP section: the path enters through authorize, checks the session, and, depending on what it finds, sends to login or directly to the callback with a new code.

Closing

Broadly speaking, that is how it works: the user's login and session live in a single place, the IdP; RP services obtain their own token by exchanging an SSO code; and on each request that token is verified against the IdP. I invite you to download the application, set breakpoints, and run tests yourself, using the seeder's credentials, to see every step with your own eyes. The document I just showed, just like my blog post, is available in the associated repository, under the v0.5 tag.

Video thumbnail

Resiliency in microservices with Laravel: circuit breaker, retries, and cache against IdP downtime

Before starting, remember that this chapter will be tagged as v0.6, so you can download it and run your tests with the exact code you are seeing. Also remember that the complete repository publication is right here, featuring a video for each tag; the only exception remains the new invoice microservice, ensuring you have full traceability across the series.

Let's recap how we got here. We started with the user and task microservices. We added observability and traceability to them. We packaged everything common using Composer. Then we added a third microservice, the invoice one. And the last thing we built was the identity provider, the IdP: a single central service that handles login and user data, avoiding the need to authenticate in each microservice or duplicate users everywhere.

Another very important topic, which we hadn't talked about yet in the entire series, is resiliency: how the application behaves when one of its dependent pieces is down or struggling. Today we will definitely dive into a lot of code, but with a conceptual introduction first: to understand the code, you need to understand the problem.

What on earth is resiliency?

Let's understand it with a simple example, broadly speaking. Remember that the user service is now the central one, the user-service: it's the identity provider, the system's single core process. With this design, to know whether an authenticated user is valid or not, all services call it: the task microservice, the invoice one — in this case, say, two examples, 10 services, 5 services, however many there might be.

Say it's a centralized cashier: you don't know if the person entering is authorized, so all modules have to ask them. And what happens if that central system doesn't work? If you have 10 processes hitting that central one with every request, and it goes down, if it receives too many requests, if memory fills up, if the disk fills up, or any other problem... exactly: that's the problem.

The concrete problem: the cashier waiting 3 seconds

Look at what we have so far, without resiliency. A client enters the task screen in the task-service and requests their list, and the authentication middleware has to validate the token. It's exactly like a cashier wanting to call the central system by phone. The central system doesn't answer, and the cashier stays with the phone to their ear waiting for 3 seconds. Why 3 seconds? Because when we make an HTTP request, the configured timeout is 3 seconds: if the other service doesn't respond, the request is aborted after 3 seconds.

  • And in the meantime, what happens to the user? They are waiting, watching the page spin without understanding anything, not knowing if it's down or not. And let's remember something important: the request the user is waiting for is also a server process waiting and consuming resources. If the request takes 3 seconds and there is a queue of 100 users, that's 100 PHP processes with the phone to their ear, resources occupied for nothing.
  • And what happens if, without thinking it through, we do what sounds logical? If the cashier realizes nobody is answering and sends the call again, and again, and again, how long will it take? If we make 2 extra attempts plus the first one, that would be 3 attempts of 3 seconds: 6 or 9 seconds with the application completely frozen for that user, and all PHP processes hanging waiting for a response, unable to know if the other service is alive or not.

The domino effect

And it gets worse. Here comes the domino effect part. If there are 2 users, peaceful ones, the system can handle it. But if the central service isn't directly dead but collapsed, and it's not 2 clients but 100 entering at the same time into a server that is already struggling... we've just finished it off. And not only that: task-service is also consuming resources, it has 100 live PHP processes, each waiting with the phone to its ear for user-service, which has already crashed.

And that's how the chain domino effect is built. We take down the central service and at the same time take down the ones querying it, even though they were never the problem. And the truth is, the rule to take away from this class is this: whoever waits, consumes. That's why resiliency is important: to make these operations as fast as possible, with a mechanism to know if the dependency is down, and to be able to respond to requests without hanging the user.

What does resiliency do? Two things

If the call fails, first: do not wait a full 3 seconds, but make super fast retries, in this case 0.15 seconds. Keep that value in mind, because it's one of the things we'll configure. And they are retries only for GET requests — data queries —, not for POST, which is a very important point we will see in the code.

Besides that, we are going to implement a new class called CircuitBreaker, which literally means an automatic circuit breaker. That's why we'll use concepts from the electrical world: closed circuit, open circuit, and a threshold to trip the breaker.

The electrical analogy, no shortcuts

If you're not an electrician don't worry, it's easily understood. A closed circuit is normal: your electrical system works, current flows, everything goes well. Translated to our application: requests flow from task-service to user-service with total normality, everything works. I, for example, saw it the other way around at first, because to me "closed" meant locking the door, cutting off passage; but here it's the electrical part: closed means the current flows, that everything is fine.

An open circuit is danger: cutting the power, pulling the cable out of the wall. The breaker trips to prevent a short circuit, for example, during a lightning strike, when your house's breaker goes down and you feel everything turn off. Translated to our application, the equivalent is: user-service failed three times in a row — very important, in a row, because if it fails twice and works on the third, the breaker doesn't trip — and then the application decides to cut the cable completely. It won't even try calling user-service for a configurable period: 30 seconds in the code. During that time, we can notify our task users: "the central service is down, we'll try again shortly". After that period, the call is tried again: if it responds, it closes the circuit and the application returns to normal; if it remains down, three more consecutive failures and it opens the circuit again.

Expressed in numbers: with the open circuit, the application doesn't make a single request to the downed server. Task or billing users instantly receive — in milliseconds — the "is down" response, instead of each being frozen for 3 seconds. And the downed server gets a break: nobody hits it for 30 seconds, which is precisely what it needs to recover.

Getting down to work: the CircuitBreaker class

Let's move to practice. This is the new class; it lives alongside the IdP HTTP client, UserServiceClient, which is the one consumed by the task and billing applications, inside the Composer package demo/microservices-user-service-client:

// packages/microservices-user-service-client/src/Resiliency/CircuitBreaker.php
<?php

namespace Demo\Microservices\UserServiceClient\Resiliency;

use Illuminate\Support\Facades\Cache;

class CircuitBreaker
{
    private const OPEN_UNTIL = 'user-service-client.circuit.open_until';

    private const FAILURES = 'user-service-client.circuit.failures';

    /**
     * The circuit is open and the cooldown has not expired.
     */
    public function isBlocked(): bool
    {
        return now()->getTimestamp() < (int) Cache::get(self::OPEN_UNTIL, 0);
    }

    /**
     * A response (even a 4xx) proves that the service is alive.
     */
    public function recordSuccess(): void
    {
        Cache::forget(self::OPEN_UNTIL);
        Cache::forget(self::FAILURES);
    }

    /**
     * Counts an infrastructure failure. Once the threshold is reached, opens
     * the circuit for the configured cooldown.
     */
    public function recordFailure(): void
    {
        $failures = (int) Cache::get(self::FAILURES, 0) + 1;

        Cache::put(self::FAILURES, $failures, now()->addHours(1));

        if ($failures >= $this->threshold()) {
            Cache::forget(self::FAILURES);

            $cooldown = max(1, (int) config('user-service-client.circuit_cooldown', 30));

            Cache::put(
                self::OPEN_UNTIL,
                now()->getTimestamp() + $cooldown,
                now()->addSeconds($cooldown + 5),
            );
        }
    }

    private function threshold(): int
    {
        return max(1, (int) config('user-service-client.circuit_threshold', 3));
    }
}

What does this class do? First, the cache is the central piece: all the breaker's state lives there. We have two constants for the two keys we use in the cache: one for the circuit opening date and another for the failure counter. Why the cache and not just in-memory properties? Because a web application serves many requests; if the breaker's state lives in memory, each request goes with a different breaker and the failure counter never reaches three. In the cache, however, all application requests share the same state.

Let's start with isBlocked(), which is the question "is the circuit open and the cooldown not expired yet?": if the date stored in cache is greater than the current time, it returns true. And as long as it returns true, we don't even attempt to make the request to user-service. That short and that safe.

recordSuccess() is what should always happen when there is a successful response: clear the cache, reset the system: deleting both the opening date key with Cache::forget() and the failure counter key. The result is quite simple: the counter goes back to zero, because the failures had to be consecutive — if it fails twice and works on the third, it's not a failure pattern, it's bad luck.

recordFailure() is the heavy part, the counter one. It's a numerical failure counter when making the request: one, two, three, four... and so on until hitting the limit. Remember it starts at 0: Cache::get(self::FAILURES, 0) + 1 — if we previously had zero, now we are at one. And we update with the new value:

Cache::put(self::FAILURES, $failures, now()->addHours(1));

Here we store the failure counter in cache with a 1-hour lifetime, which is just a ceiling: the maximum time the counter survives in cache if the application goes idle; it's not the cooldown. And here comes the important part: when the counter reaches the threshold, we open the circuit:

if ($failures >= $this->threshold()) {
    Cache::forget(self::FAILURES);

    $cooldown = max(1, (int) config('user-service-client.circuit_cooldown', 30));

    Cache::put(
        self::OPEN_UNTIL,
        now()->getTimestamp() + $cooldown,
        now()->addSeconds($cooldown + 5),
    );
}

Here is threshold(), which dictates how many consecutive failures we will allow: three. And it's a smart detail: we don't store "3 failures", but rather calculate a future date. The current time now()->getTimestamp() plus the 30 seconds of cooldown. And that date is what isBlocked() queries: "is what's in cache greater than now?". As long as that date is in the future, isBlocked() returns true. When it expires, the cache itself takes care of deleting it and the circuit is ready to return.

Configuration: five resiliency values

These values are neither invented in code nor hardcoded, but reside in the package configuration, config/user-service-client.php, under its Resiliency section:

// packages/microservices-user-service-client/config/user-service-client.php
// Resiliency
'retries' => (int) env('USER_SERVICE_RETRIES', 2),

'retry_delay_ms' => (int) env('USER_SERVICE_RETRY_DELAY_MS', 150),

'cache_ttl' => (int) env('USER_SERVICE_CACHE_TTL', 60),

'circuit_threshold' => (int) env('USER_SERVICE_CIRCUIT_THRESHOLD', 3),

'circuit_cooldown' => (int) env('USER_SERVICE_CIRCUIT_COOLDOWN', 30),

That is: 2 retries, meaning up to 3 attempts including the first one; a 150-millisecond pause between retries; 60 seconds of user verification caching (we'll explain this in the middleware); the breaker threshold of 3 consecutive failures; and the cooldown (the time the circuit remains open) of 30 seconds. And how do I change them if I want? As always in Laravel: an env() with its default value. If the variable is defined in .env, the .env value wins; if not, it keeps the default value we programmed with. If tomorrow in production you want to open the circuit at 5 failures and leave the cooldown at one minute, done: USER_SERVICE_CIRCUIT_THRESHOLD=5 and USER_SERVICE_CIRCUIT_COOLDOWN=60. Everything configurable, nothing hardcoded:

USER_SERVICE_RETRIES=2
USER_SERVICE_RETRY_DELAY_MS=150
USER_SERVICE_CACHE_TTL=60
USER_SERVICE_CIRCUIT_THRESHOLD=3
USER_SERVICE_CIRCUIT_COOLDOWN=30

Where it hooks in: the UserServiceClient client

Now then, who consumes this class? The breaker is consumed by the central class of the package, UserServiceClient, which is precisely the class that task-service and billing-service talk to with user-service: it handles login, logout, token verification, and SSO code exchange. This class already existed since the Composer package tag; now its constructor receives one more dependency:

// packages/microservices-user-service-client/src/UserServiceClient.php
class UserServiceClient implements IdentityProvider
{
    public function __construct(private readonly CircuitBreaker $breaker) {}
}

Laravel resolves it automatically, because this CircuitBreaker receives no dependencies in its constructor: zero configuration, zero service providers to build manually.

And where is the breaker used? In send(), which is the method where all methods talking to user-service arrive: authenticate(), which verifies the token; issueToken(), which handles login; revokeToken(), which handles logout; and exchangeCode(), which exchanges the SSO code. All actual HTTP requests of the package pass through the same funnel, and the funnel is instrumented with the breaker. Let's look at the beginning of the method itself, which is the first thing that appears:

private function send(callable $callback, bool $retryable = false): Response
{
    if ($this->breaker->isBlocked()) {
        throw new UserServiceUnavailableException(
            'The user-service is not available (circuit open).'
        );
    }

Notice: open circuit means no HTTP request is made. We say "it's down", we fail in milliseconds — throwing the service unavailable exception — and we don't even touch the server, so it can recover as well. And this exception we throw, UserServiceUnavailableException, is not new: it already exists since the package tag, and both task and billing already map it to a 503 page with its explanation. What is new is not what the application responds, but how fast: in milliseconds, not in 3 seconds.

And since both task-service and billing-service use the same package src, this improvement is free for both: zero changes in the two applications for the circuit.

Retries: the for loop

Next comes the retries part. Notice that the method has a new parameter, $retryable: it states whether the request supports retries. We'll see it in a moment. First, the loop:

$attempts = $retryable
    ? 1 + max(0, (int) config('user-service-client.retries', 2))
    : 1;
$delayMs = max(0, (int) config('user-service-client.retry_delay_ms', 150));

for ($attempt = 1; ; $attempt++) {
    $last = $attempt === $attempts;

    try {
        $response = $callback();
    } catch (ConnectionException $exception) {
        // Each failed connection attempt is additional evidence.
        $this->breaker->recordFailure();

        if ($last) {
            throw new UserServiceUnavailableException(
                'Could not contact the user-service.',
                previous: $exception,
            );
        }

        usleep($delayMs * 1000);

        continue;
    }

Here is the math: the for starts at 1, attempt one is the normal attempt; if the request is retryable, attempts equal 1 plus the retries configuration — 1 + 2, meaning 3 attempts in total —, and the time between attempt and attempt, retry_delay_ms, is 150 milliseconds. The request itself is not written here: it is passed as $callback from the methods above — that's the beauty of a callable: the loop calls it as many times as it wants.

When a ConnectionException occurs — the connection to the downed server could not be made — we catch it, and the first thing we do is add a failure to the counter with recordFailure(). If there are still turns left — it's not the last attempt — we sleep for 150 milliseconds with usleep — remember that usleep works in microseconds, hence the * 1000 — and do continue: repeat the loop, make the call again. If it was the last attempt, we exit by throwing the service unavailable exception, and notice the detail: we pass it with previous: pointing to the original exception, so that logs keep the root cause and not just the symptom.

The final stretch of the for: who lives, who dies

And the last block of the loop, where the two remaining things happen:

// The circuit only cares about infrastructure: even a
// 4xx proves that the IdP is alive and responding.
if ($response->successful() || $response->clientError()) {
    $this->breaker->recordSuccess();

    return $response;
}

if ($last || ! $retryable) {
    if ($response->serverError()) {
        $this->breaker->recordFailure();
    }

    return $response;
}

usleep($delayMs * 1000);
}
}

First: if the response was successful, we clear the cache with recordSuccess() and return the response. Remember "consecutive": the three failures have to be back-to-back; if it fails twice and on the third the request works, the breaker doesn't trip — the counter goes back to zero and we are at peace.

And watch out for the HTTP codes detail. What happens if the response is a client error, a clientError(), a 4xx? Well, we also count it as a success: even a 4xx proves that the server is alive. Think about it: a 401 for "invalid SSO code" is given by a server that is awake, responding, connected; when dead, it doesn't answer even if you hit it. If the circuit is open and a 4xx arrives, that 4xx is evidence of life: the counter is cleared and the circuit closes. The only thing that counts as a failure — as evidence of broken infrastructure — are 5xx, server errors, and only when there are no retries left: that's why if ($response->serverError()) goes inside $last. A 5xx midway through the loop only triggers a retry; a 5xx on the last attempt adds its failure and the response bubbles straight up.

What gets retried and what doesn't?

This is the key question, and that's what the $retryable parameter is for. The three methods of the class call send() through their helpers:

// GET (authenticate) and DELETE (revokeToken) are idempotent: they can be retried.
return $this->send(fn () => Http::acceptJson()
    ->withHeaders($headers)
    ->timeout($this->timeout())
    ->get($this->baseUrl().$uri), true);

// POST (exchangeCode, issueToken) are NOT retried:
// the SSO code is single-use. They pass through send only once.
return $this->send(fn () => Http::acceptJson()
    ->asJson()
    ->withHeaders($headers)
    ->timeout($this->timeout())
    ->post($this->baseUrl().$uri, $payload), false);

GET requests — like authenticate(), verifying the token — and DELETE requests — like revokeToken(), logout — are idempotent: calling them twice changes nothing in the world. Repeating a token validation is repeating a read; repeating a logout is revoking an already revoked token. Those can indeed be retried, which is why they pass true.

POSTs do not. And this is the point I anticipated at the beginning. As you saw, the POSTs made by the client are exchangeCode() — exchanging an SSO code — and issueToken() — login. Both emit things that get consumed: the SSO code is single-use, and a newly issued token already exists. If we send the request again, the code has already been exchanged and would return a 400; and a repeated login would issue extra tokens. Retrying blindly is the best way to manufacture weird errors. POSTs pass through send() with false: a single attempt, and let happen what must happen.

The second optimization: caching in the middleware

The second optimization is not in the client class, but in another file of the package, in the authentication middleware, AuthenticateWithUserService, the one that runs every time we access task or billing routes. In its private method that does everything, resolveUser(), the flow until now was simple: a token arrived and was asked to user-service, plain and simple.

The logic we apply is exactly the one I described when explaining "I trust you" in the video: "hey, if I just verified this user three seconds ago, with exactly this token, and now you ask me again... it doesn't make much sense to ask. Three seconds ago I told you it was correct: I trust you". So we cache the verification result:

// packages/microservices-user-service-client/src/Http/Middleware/AuthenticateWithUserService.php
private function resolveUser(string $token): ?array
{
    $ttl = max(0, (int) config('user-service-client.cache_ttl', 60));

    if ($ttl === 0) {
        return $this->users->authenticate($token);
    }

    $key = self::USER_CACHE_PREFIX.hash('sha256', $token);

    $cached = Cache::get($key);

    if ($cached !== null) {
        return $cached['user'] ?? null;
    }

    $user = $this->users->authenticate($token);

    Cache::put($key, ['user' => $user], now()->addSeconds($ttl));

    return $user;
}

Let's comment: first, the cache key is USER_CACHE_PREFIX plus the SHA-256 hash of the token. The prefix is just to avoid colliding with other cache keys the application might use for other things. And why the token hash and not the token? For hygiene: the token is a secret; storing it as-is in a cache that might be file-based on disk and shared means storing secrets in plain text. The hash is a value that doesn't allow reconstructing the original.

And the time? That's cache_ttl: 60 seconds. We kill two birds with one stone: less latency for the user — their task page no longer pays an HTTP hop on every click — and less pressure on user-service, which goes from receiving one verification per page to one per user per minute.

Fine details. First: if it's 0, we disable it — and then we are forcing always, and not just sometimes, every request to go through authenticate(), the contract method of IdentityProvider that makes the blessed HTTP request, just like we had before. With this single line you recover strict behavior; it's your call, not an obligation.

Second: we also cache the negative result. See the ['user' => $user]? When the token is invalid, authenticate() returns null, and that null is also stored in cache for the 60 seconds. Without that, a stolen or rotten token that an attacker tried a thousand times per second would hit the IdP a thousand times per second. Thus, the "no" is also remembered, and the IdP sees one verification per token rather than a hammer-blow. And watch out for another thing: if the IdP is down, the verification that would fill the cache never happens — the request throws an exception —, meaning the cache doesn't get dirtied with false results and the open circuit takes over. Everything neatly bounded.

The numbers: what is gained

And what is this worth in practice? Measured for real in the actual project: all three services up, real login via SSO flow, and a kill -9 to user-service mid-session:

PhaseWhat happensMeasured result
Live cacheIdP dead, same session, refreshing the tasks page200 in 11 ms — the user doesn't notice the outage
No cache, first requestCache doesn't have the token: time to actually validate, circuit hasn't opened yet503 in 341 ms, previously 3000 ms
No cache, subsequent requestsCircuit already opened due to its 3 consecutive failures503 in 5 ms — without touching the network
RecoveryI boot up the IdP; still blocked by cooldown503 in 11 ms; after 30 s, 200 again

Look at the second row, because that's where the effect of cold retries lies: it's not magic, it's 3 real attempts — the first fails immediately because the connection is refused, and the next two after their 150 ms wait — except instead of 3 frozen seconds per attempt, they are millisecond attempts. If the IdP were collapsed but not dead, those super-fast retries would be the difference between a request going through and 100 users dropped.

And an important detail: none of the pieces invent a new error type for the application. The breaker throws the same exception — UserServiceUnavailableException — that was already rendered with a 503 page explaining to the user how to start the other service. What's new is not what the app says, but when: instead of after 3 seconds, instantly.

As I've been repeating to you for several chapters: as much as possible, we should run away from microservices, and use them only when truly necessary, when scale or team demands it. Keeping all of this afloat — security, deployments, and now also resiliency — is not free, and that's why we've spent most of the series building infrastructure, while the real application, two CRUDs and out, hasn't changed.

JSON Web Token for Authentication: Local Verification

Video thumbnail

Now we are going to introduce what the JSON Web Token is for our application, our microservices system; with this, we already have more secure authentication. And on the other hand, there is no need to keep sending requests to the user service every time we want to navigate through the tasks CRUD. And right now we are going to log in and I will explain a bit more.

For example, once logged in, we can have the user service turned off and the application will keep working perfectly. We can already perform verification locally, in the client application itself. So, otherwise, the flow remains exactly the same. I am going to show you which files were changed.

So, the current system will support both implementations: the famous opaque token, which was the previous implementation, and the JSON Web Token. And we can switch via a simple configuration:

user-service/.env

TOKEN_MODE=jwt

The idea is that for our JSON Web Token we will have signed public and private keys. They will live right here, inside our user application; here we have them, the public and private keys. To generate them we have an Artisan command that generates these keys and then, through a controller that I will show you when we move to the implementation, we simply read the keys to generate the JSON Web Token. Just like any service today, where, for example, PayPal, for example, Stripe, always manage a public and a private key—you have to do the exact same thing:

$ php artisan user-service:jwt-keys

user-service/app/Console/Commands/GenerateJwtKeys.php

$key = openssl_pkey_new([
    'digest_alg' => 'sha256',
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);

The public key can be accessed in the following way. Notice that it will be from the user application, the user service. And therefore, it will be consumed by the client applications, which would be the tasks and billing ones. And obviously the private key remains private to generate said token:

curl http://127.0.0.1:8000/api/jwks.json
{
  "keys": [{
    "kty": "RSA",
    "use": "sig",
    "alg": "RS256",
    "kid": "e64e4ca4bb8d7e2a",
    "n": "0wzG…",
    "e": "AQAB"
  }]
}
  • "kty": "RSA" (Key Type): Indicates the cryptographic algorithm used, in this case RSA (the asymmetric key cryptography standard based on the factorization of large prime numbers).
  • "use": "sig" (Key Use): Specifies what the key will be used for. Stands for Signature; meaning, this key is used exclusively for signing and verifying digital signatures, not for encrypting confidential data.
  • "alg": "RS256" (Algorithm): Defines the exact signing algorithm to be used with this key: RSASSA-PKCS1-v1_5 with SHA-256. It is the standard algorithm required by the JwtVerifier to validate the token.
  • "kid": "e64e4ca4bb8d7e2a" (Key ID): It is the unique identifier of the key (the "version number"). It allows the system to know exactly which key to use if several are available, or to detect when the IdP has rotated the keys to force a cache update.
  • "n": "0wzG…" (Modulus): It is the RSA modulus, one of the two large prime numbers that make up the mathematical foundation of the public key. It is encoded in Base64URL. The JWT library uses this value along with the exponent to reconstruct the public key mathematically and check if the token signature is legitimate.
  • "e": "AQAB" (Exponent): It is the public exponent (generally the standard value 65537, represented here in Base64URL as AQAB). Along with the modulus n, it completes the public key required for verification.

Otherwise, we have some services to, for example, generate the key, obtain the credentials shown moments ago—generated through the Artisan command—and also check it:

user-service/app/Services/Jwt/JwtKeys.php

public function privateKey(): string { ... }   // the private one, only here
public function publicKey(): string { ... }    // the public one
public function kid(): string { ... }          // key id, derived from its hash
public function jwks(): array { ... }          // the public one in JWKS format
public function keySet(): array { ... }        // keyset for local verification

So, at this point we can move a bit into the implementation. Before starting as well, notice which files are affected. Notice that, for example, for tasks absolutely nothing changes, just like for billing, because they are practically the same type of services. Absolutely nothing changes, except for a test that was adjusted and also the .env file. Therefore, notice that the clients, so to speak, remain exactly the same, and switching from one authentication method to another is completely transparent, thanks to the good schema we have.

USER_SERVICE_JWKS_URL=http://127.0.0.1:8000/api/jwks.json
USER_SERVICE_JWT_ISSUER=user-service
USER_SERVICE_JWT_LEEWAY=10
USER_SERVICE_JWKS_CACHE_TTL=3600

The previous flow is maintained

What was explained previously is also maintained, we had these controllers that run before making any request, to see if we are authenticated or not; and if we are not authenticated, for example when we are going to move from tasks to billing, we send the token so that we don't have to authenticate the billing application again if we came from the tasks one. All of that is maintained. Likewise, we are going to review the flow a bit so that everything is a bit clearer.

So, let's remember: it all starts with this middleware we have here, which is configured like an alias. Therefore, here we have what the middleware we are actually using really is:

// task-service/routes/api.php
Route::middleware('auth.user-service')->group(function () {
    Route::apiResource('tasks', ApiTaskController::class)->names('api.tasks');
});

Notice, by the code, that it remains exactly the same. What changes is that now we are no longer using a crappy token that we generated ourselves through a hash, but rather we are employing a JSON Web Token with all the advantages this brings us: basically, having the public key, we can decode it and know if it is a valid token or not. Therefore, here we have an important optimization, because this token is representative: it is not just a representation to know if we are authenticated or not, but we can also extract information from it, and with that know if it is valid or not and act accordingly. So, this remains exactly the same.

The Identity Provider: that's where the change is

Here we have the Identity Provider, and there we do have an important change—we'll come back to the provider. Let's remember that it all starts right here, with the authentication methods, which reject or pass. Here, in the provider part, we already have some registrations; notice, some additional singletons that are for the JSON Web Token, we will analyze them shortly. But here we have a fundamental change, and that's why everything is completely transparent:

packages/microservices-user-service-client/src/UserServiceClientServiceProvider.php

$this->app->singleton(JwkKeyStore::class);
$this->app->singleton(JwtVerifier::class);

// Since v0.6 the default verifies JWT locally (with JWKS refetch and the
// fallback HTTP client for opaque ones and for issuing).
$this->app->bind(IdentityProvider::class, JwtIdentityProvider::class);

Remember that previously one called IdentityProvider had been implemented, which is simply an interface: authenticate with its token, and what you can read there. And before, this was not what we had, obviously, because this is new. If you check—well, I'll check the GitHub repository right now—we had one called UserServiceClient, which of course still exists because, as mentioned at the beginning, we allow both authentication systems, and this one continues to be maintained here. I'm leaving it present here so you can keep it in mind.

Here are the corresponding controllers and now we have one called JwtIdentityProvider. Therefore, it is completely transparent: just as you saw moments ago, when the IdentityProvider is loading, it is not loading its interface, but its implementation. And we resolve the implementation right here, where we match the interface and the class implementing that interface.

Comparing with what we had before

And here you can see the catch, that is, why this type of structure is used: this is object-oriented programming in all its glory. Obviously it will implement exactly the same methods we had before. And at this point we can compare them a bit so you can see exactly what changes.

Here remember that in the authenticate of the previous implementation what we always, always did was make a request to the user application, to the user service. And that is why after releasing this class we implemented resilience, to avoid, well, practically killing the poor user service—as mentioned before: if we have 100 users connecting at the same time and the server is overloaded, we are going to finish killing it. That's why we implemented a resilience structure, which is good to know because it can serve you for other things. But in this case, the cleanest solution is precisely that of the JSON Web Token: with this we practically saved the request we made previously. Remember that these are educational resources and therefore we vary between one implementation and another; but the previous implementation is retired when something better arrives.

Now, what are we implementing in the JWT? Notice that for the new implementation—the JwtIdentityProvider I mentioned moments ago in the provider—we no longer make the previous connection here. Over there we had—always, always—the connection to the user service, and now we no longer make it here. Everything stays perfectly local, with the advantages this brings us: we don't have to make a network request, saving us those resources:

packages/microservices-user-service-client/src/Jwt/JwtIdentityProvider.php

public function authenticate(string $token): ?array
{
    $user = $this->verifier->verify($token);   // ← verification is LOCAL

    if ($user !== null) {
        return $user;
    }

    if (substr_count($token, '.') === 2) {
        return null;   // it had a JWT shape and did not validate
    }

    // Does not look like JWT: it's the opaque token. HTTP client, the old way.
    return $this->clients->authenticate($token);
}

So, how is it done? All verification is done right here locally. Notice that this call to verify of JwtVerifier is made here, and we'll analyze it soon. Basically: we pass the token just like before, and here it basically discriminates whether it's the old token (the traditional scheme) or if it's the new one, whose format is basically a different structure. If this is not met and we don't have a user, then we have problems: we return a null—and you have to request login again and all the flow I showed you before; that's what the class told you about the flow with SSO. And notice the beauty of this: if you want to implement or use the previous implementation for any reason, you call authenticate of UserServiceClient—that's why I mentioned that this class still exists with what we had before.

Notice that this $clients we now have here in the constructor points to our UserServiceClient:

return $this->clients->authenticate($token);

To be clear: this should not be used, and in a real application you could perfectly remove it. But again, for didactic purposes, and so you can see that these types of implementations can be made—for educational reasons, you have multiple ways of authentication—you might end up using this. And how nice and structured that is.

The new IdP files

Otherwise, what is maintained here is the normal management flow of the JSON Web Token, and we'll analyze it now. Now yes: here we can analyze a bit these files which are what we have here. They have the description right here, in case you get a bit lost.

First, this pair of configurations pointing towards the directories shown before, where we have our credentials:

user-service/config/jwt.php

'private_key' => env('JWT_PRIVATE_KEY', storage_path('app/jwt/jwt-private.pem')),
'public_key'  => env('JWT_PUBLIC_KEY',  storage_path('app/jwt/jwt-public.pem')),

This first file—JwtKeys—reads these files to get the content, get the public key, and then be able to generate the JWKS URL and so on. Here is the kid, which is the public key identifier derived from its hash. Here also, by the way, is the custom Artisan command created by us to generate these keys, and you can override it there.

Otherwise, here we have one that verifies the token: it receives the token and checks whether it is valid or not:

user-service/app/Services/Jwt/JwtTokenVerifier.php

try {
    JWT::$leeway = max(0, (int) config('jwt.leeway', 10));

    $claims = JWT::decode($token, $this->keys->keySet());
} catch (\Throwable) {
    return null;
}

if ((string) ($claims->iss ?? '') !== (string) config('jwt.issuer')) {
    return null;
}

return (array) $claims;

And this other service, JwtTokenIssuer, what it does is generate the token. Notice that here we have user information; since—again—here we are with real information: therefore, when we decode it we can know if it is valid or not and, obviously, also know if it has expired or not. Therefore, there is no need to make a request to the user service:

user-service/app/Services/Jwt/JwtTokenIssuer.php

$payload = [
    'iss' => (string) config('jwt.issuer'),   // issuer: user-service

    'sub' => (string) $user->id,              // the identity snapshot
    'name' => $user->name,
    'email' => $user->email,

    'iat' => (int) $issuedAt->getTimestamp(), // when it was issued
    'exp' => (int) $expiresAt->getTimestamp(),// when it expires (iat + TTL)

    'jti' => bin2hex(random_bytes(16)),       // unique token id
    'device_name' => $deviceName,
];

$token = JWT::encode($payload, $this->keys->privateKey(), 'RS256', $this->keys->kid());

And in this other class, AccessTokenIssuer, it is determined whether it is our JSON Web Token or the token we had previously, and well, it returns it. That's why the implementation is extremely clean: in the end, it's a token that is handled the exact same way. Understand that "it is handled the exact same way" refers to the initiated or defined session. What changes is the way to generate it, obviously, and from there the advantage it brings us, which I mentioned before: it already brings user data, and here you can see the flow a bit. And obviously this is where the token is generated:

user-service/app/Services/Jwt/AccessTokenIssuer.php

if (config('tokens.mode') === 'jwt') {
    $issued = $this->jwtIssuer->issue($user, $deviceName);

    return [
        'token' => $issued['token'],
        'token_type' => 'Bearer',
        'expires_at' => $issued['expires_at']->toIso8601String(),
        'api_token' => null,   // no row in any table
    ];
}

// opaque mode: the token from the whole series up to b0.6, intact

This is the one that determines which one we call, and the AccessTokenIssuer is the one used directly from the application. For example, notice that the endpoint part to issue the token—point at which we finally arrive—: here we have the service as part of the AuthController constructor. As before: we verify credentials and generate the corresponding token. It's simply searching by names and seeing exactly where it is being used, to see how it works:

user-service/app/Http/Controllers/AuthController.php

public function __construct(private readonly AccessTokenIssuer $accessTokens) {}

public function store(Request $request): JsonResponse
{
    $validated = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required', 'string'],
        'device_name' => ['sometimes', 'string', 'max:100'],
    ]);

    $user = User::query()->where('email', $validated['email'])->first();

    if (! $user || ! $user->passwordMatches($validated['password'])) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }

    $issued = $this->accessTokens->issue($user, $validated['device_name'] ?? 'api-token');
}

For this, by the way, for the JSON Web Token we are not using Sanctum, because nothing of that paints a picture here. We are using a package called firebase/php-jwt, which is a Firebase library, a package quite used in PHP precisely for the encoding and decoding JWT part:

"firebase/php-jwt": "^7.2",

The kid and the public key cache

Surely you also saw a definition called kid—key identifier. This is simply a key. Notice that here we already have a flow in the JwkKeyStore, and it is precisely for when keys are regenerated for any reason. Then notice that here we already have a cache to avoid consuming the public key shown previously every single time. Basically, when we have a different key—plus others we have cached—a reload is forced. You can see it here: force: true to make the network request again:

packages/microservices-user-service-client/src/Jwt/JwkKeyStore.php

$raw = $this->raw(force: false);

if ($missingKid !== null && ! $this->hasKid($raw, $missingKid)) {
    $raw = $this->raw(force: true);   // the already cached JWKS does not have that kid
}

return JWK::parseKeySet($raw, 'RS256');

And that is why, unlike resilience—the circuit breaker—for this implementation it is practically not being used, because everything always remains cached.

The test: with the user service turned off

If you authenticate using the new scheme and stop the user service, before it failed, it crashed; we couldn't do any operation from the tasks/bills app. Now we can work perfectly, for what was mentioned before. Because now this token—and you can check it in the code—what it does is first try to decode the token. If an exception is thrown—that the token is crappy, not signed as it should be, corrupted, expired, whatever—we return a null. And once decoded, if certain key information does not match—for example, if the iss is null or, for example, does not match what our user-service is in the app configuration being used—then it is null again; if it's fine, it goes ahead:

// packages/.../src/Jwt/JwtVerifier.php
try {
    JWT::$leeway = max(0, (int) config('user-service-client.jwt.leeway', 10));

    $claims = JWT::decode($token, $this->keys->keySet($this->kidOf($token)));
} catch (\Throwable) {
    return null;   // expired, corrupted signature, unknown kid...
}

if ((string) ($claims->iss ?? '') !== (string) config('user-service-client.jwt.issuer', 'user-service')) {
    return null;
}

return [
    'id' => (int) $claims->sub,
    'name' => (string) $claims->name,
    'email' => (string) $claims->email,
];

ISS is simply issuer, in case you were wondering; and what is the issuer? Our user service.

Problem

Problem we currently have: the token is not being stored anywhere. Therefore, what happens if there is a stolen token that we want to delete? Well, things are not simple: practically with the structure we currently have it is impossible to delete the token. What does support us is that the token's lifetime is short—configurable, fifteen minutes—and upon expiration it disappears.

But otherwise we achieve something important in microservices, which is independence between services. Since again the tasks one goes its own way, billing goes its own way, and it doesn't care at all if one of the two has gone down: you can access it perfectly. And always the Achilles' heel was the user one, which was the central one. But notice that with this implementation we simply authenticate once, generate the token, and for however long you want to stipulate in the cache you can use the rest of the application regardless of whether the user one went down or not: the application will continue to work—not for a few seconds or a few minutes, as happened with resilience, but for hours or days. And that depends on how much expiration time you want to give the tokens.

Queues and Events: Asynchronous Communication Between Microservices

Another very interesting topic is communication between microservices. For this case, let's assume that when we create a task, we want to create an invoice. To do this, let's remember that we have the task service, where we will obviously create the task, and when it is completed, we will create an invoice in the billing service. Therefore, we send a message from one microservice to the other. And the interesting thing here is this: seeing how the system works and how we can make this type of connections, since it is basically the heart of using microservices.

Right now the communication we have is strictly synchronous: we send an HTTP request and wait for a response. Now we have a new package with which we will be able to handle asynchronous communication based on job queues. As mentioned before: when a task is completed, we are going to mark an associated invoice in the billing service, simple as that. To do this, we are going to dispatch from the tasks, right at the moment that happens, an event that billing later consumes with its worker — the corresponding artisan command. Also remember that I already have an article here about queues and jobs. And well, basically we create an invoice. In principle it sounds simple, but the matter is a bit more complicated, as always, than it seems. Let's go a bit into practice to see what we have.

The package and its configuration

Here in the packages we have a new package, demo/microservices-events, through which we have a configuration for events, a bit always the same. A timeout, how many attempts — meaning that in queues and jobs there can always be a problem with a particular transporter and then it tries again: here we are customizing it. The backoff is the strategy to wait between attempts: first 10, then 30, then 120 seconds. And this is the maximum time, the max age, with which if the message arrives 120 seconds later, the system basically rejects it because it is already too old, etc.

task-service/config/events.php

'subscribers' => [
    'billing' => [
        'url' => env('BILLING_EVENTS_URL', 'http://127.0.0.1:8002/api/events'),
        'secret' => env('BILLING_EVENTS_SECRET'),
        'events' => ['task.completed'],
    ],
],

Operational defaults (timeout, retries, backoff, anti-replay) live in the package, and this is the configuration part that each application adjusts if anything differs:

packages/microservices-events/config/events.php

'timeout' => env('EVENTS_TIMEOUT', 3),         // seconds per HTTP attempt
'max_attempts' => env('EVENTS_MAX_ATTEMPTS', 5),
'backoff' => env('EVENTS_BACKOFF', [10, 30, 120]),
'max_age' => env('EVENTS_MAX_AGE', 120),       // receiver freshness window

The custom outbox migration

There is a new migration to handle events. Notice that it is a custom system and not directly the framework's queues and jobs one: we wouldn't use the jobs table, but everything first originates right in this table. It is the outbox pattern: events are rows in our local database.

packages/microservices-events/database/migrations/0001_01_01_000003_create_outbox_tables.php

// 
Schema::create('outbox_events', function (Blueprint $table) {
    $table->id();
    $table->uuid('event_id')->unique();
    $table->string('type')->index();
    $table->json('payload');
    $table->string('trace_id')->nullable()->index();
    $table->timestamp('occurred_at');
    $table->timestamp('available_at')->index();
    $table->timestamps();
});

Schema::create('outbox_deliveries', function (Blueprint $table) {
    $table->id();
    $table->foreignId('outbox_event_id')->index()->constrained()->cascadeOnDelete();
    $table->string('subscriber')->index();
    // One attempt per event/subscriber: no duplicate deliveries either.
    $table->unique(['outbox_event_id', 'subscriber']);
    $table->string('status')->index();
    $table->unsignedInteger('attempts')->default(0);
    $table->string('last_error')->nullable();
    $table->timestamp('available_at')->index();
    $table->timestamp('delivered_at')->nullable();
    $table->timestamps();
});

The package command and middleware

An artisan command to listen for events that occur when we start a new job: outbox:dispatch. And a piece in the package is to verify the signature, because obviously all of this comes with its hash and so on: it's about guaranteeing that it's not a job slipped in from outside the system, that it is the system. And some classes that manage this whole system based on a protocol called outbox.

The outbox classes

At this point I am going to explain them from here. The OutboxEvent, the PHP class or file, is the model of what the event represents. You can see it here: it is simply a model — event_id, type, payload, trace_id, dates:

packages/microservices-events/src/Outbox/OutboxEvent.php

public static function record(string $type, array $payload, ?string $traceId = null): self
{
    return self::query()->create([
        'event_id' => (string) Str::uuid(),
        'type' => $type,
        'payload' => $payload,
        'trace_id' => $traceId,
        'occurred_at' => now(),
        'available_at' => now(),
    ]);
}

The OutboxDelivery is a model that records when we send messages between microservices, since in principle one could send an event to multiple microservices. In this case it wouldn't be like that, but this table keeps all that trace:

packages/microservices-events/src/Outbox/OutboxDelivery.php

#[Fillable([
    'outbox_event_id',
    'subscriber',
    'status',          // pending | delivered | failed
    'attempts',
    'last_error',
    'delivered_at',
    'available_at',
])]
class OutboxDelivery extends Model { /* attempts and dates casts */ }

The OutboxDispatcher: what this class does is scan the database looking for pending events. Notice that the key piece would be the following check, in which it searches for events it has to process. Understand available_at, which specifies when it is going to be available — we can place a future date — well: that they are already available and returns them. This is simply what says "events that have to start working":

// packages/microservices-events/src/Outbox/OutboxDispatcher.php
public function dispatchPending(?int $limit = 50): int
{
    $delivered = 0;

    OutboxEvent::query()
        ->with('deliveries')
        ->where('available_at', '<=', now())     // its backoff has not expired yet
        ->orderBy('occurred_at')
        ->limit(max(1, (int) $limit))
        ->get()
        ->each(function (OutboxEvent $event) use (&$delivered): void {
            foreach ($this->subscribersFor($event->type) as $name => $subscriber) {
                // It is a firstOrCreate: an (event, receiver) does not have two
                // pending deliveries. If it is already 'delivered' or 'failed',
                // we do not resend it here.
                $delivery = $this->ensureDelivery($event, (string) $name);

                if ($delivery->status !== 'pending') {
                    continue;
                }

                if ($this->deliverTo($event, (string) $name, $subscriber, $delivery)) {
                    $delivered++;
                }
            }
        });

    return $delivered;
}

And the class in charge of cryptography, for security reasons: that nobody can update or create an event outside the system to try to hack us or whatever. The signature is an HMAC over the exact body that travels, and the receiver compares it in constant time with hash_equals:

packages/microservices-events/src/Outbox/Signature.php

public static function sign(string $body, string $secret): string
{
    return hash_hmac('sha256', $body, $secret);
}

public static function verify(string $body, string $secret, string $signature): bool
{
    $given = trim($signature);

    if ($given === '' || (bool) str_contains($given, ' ')) {
        return false;
    }

    return hash_equals(self::sign($body, $secret), strtolower($given));
}

The event: TaskCompleted

The event originates somewhat in the following flow: in TaskCompletion, which is a service we have in task. Clearly an event is registered there. And here we must have an activated command, which is the outbox dispatcher's. Notice that here, in the commands part, we are looking for — look — events to dispatch every minute. Therefore, this is a separate process: this would be placed in the cron. In this case, since we don't have a cron, what we have to do is simulate it in a development environment.

The task-service side flow

Let's look a bit at the flow. Notice that in tasks here you can see the files that were changed and created: the one for tasks, for the store() that creates and the update(), and we have a service called TaskCompletion which, if we analyze it, what it does is mark a task as completed. When it has been completed, it performs an atomic transaction with DB::transaction() here, which we also saw in the course. Remember what this does: it executes all of this in the same transaction; if one fails, the other does too, and reverts the changes.

And this is due to the pattern we are using. The outbox pattern (Transactional Outbox Pattern) is a software architecture solution designed to solve a specific problem in distributed systems — microservices, in this case — and it is the problem of database dual writes. That is why this pattern tells us that everything must be atomic: that is why we use a transactional operation, just as you can read here. And then its subsequent dispatch, independently, through the commands we saw before: everything that has to do with queues and jobs and cron is separate, independently of the main application thread. And the third point is that it has fault tolerance and retries, which was what I explained earlier in the structure I presented to you. As I tell you, this has plenty of ground to cover and I am simply presenting some code so you understand what all this is about, but you have to deepen a bit more by doing your own tests.

task-service/app/Services/TaskCompletion.php

public function complete(Task $task, array $actor, array $attributes = [], ?string $traceId = null): void
{
    // It is already completed: it is idempotent (a repeated PUT does not re-emit).
    if ($task->status === Task::STATUS_COMPLETED) {
        return;
    }

    DB::transaction(function () use ($task, $actor, $attributes, $traceId): void {
        $task->update([...$attributes, 'status' => Task::STATUS_COMPLETED]);

        // Same transaction: if the task doesn't survive, neither does the event.
        OutboxEvent::record('task.completed', [
            'task_id' => $task->id,
            'task_title' => $task->title,
            'user_id' => $task->user_id,
            'actor' => $actor,
        ], $traceId);
    });

    // The email goes into the usual queue (Laravel's own jobs): with
    // QUEUE_CONNECTION=sync it goes out inline; with database, a worker
    // picks it up later. In both cases, the HTTP request no longer waits for it.
    SendTaskCompletedEmail::dispatch($task->fresh(), $actor)->onQueue('mails');
}

Here what it is asking is whether the task has already been completed; then it simply does nothing, since it is complete, it is updating a task in this case — the user completed it — and therefore the invoice will have already been generated in another process that we are about to see. But if it has not been marked as completed, then, watch out, notice the flow here: what matters is the state the user wants to set.

task-service/app/Http/Controllers/TaskController.php

public function update(UpdateTaskRequest $request, int $task, TaskCompletion $completion): RedirectResponse
{
    Log::info('The user updated a task');

    $model = $this->findOwnedTask($task);

    if (($request->validated('status') ?? $model->status) === Task::STATUS_COMPLETED
        && $model->status !== Task::STATUS_COMPLETED) {
        $completion->complete($model, $this->actor(), $request->validated(), $this->traceId());
    } else {
        $model->update($request->validated());
    }

    return redirect()
        ->route('tasks.index')
        ->with('success', 'Task updated successfully.');
}

Notice that on one hand we are looking for the task in the database, precisely by the identifier; we look for it and notice that we are asking from the request, meaning the user's request that precisely changed it to completed. It is precisely when this operation is called, and of course that the status we had in the database is not completed — again because of what was mentioned before, because this process only has to be called once, when the task transitions to completed (it doesn't matter what its status was, but that it's not completed, and you can see it here with the question). And this is by user selection; that is why we ask from the validated data. The "task completed" operation is called.

task-service/app/Http/Controllers/TaskController.php

public function update(UpdateTaskRequest $request, int $task, TaskCompletion $completion): RedirectResponse
{
    $model = $this->findOwnedTask($task);

    if (($request->validated('status') ?? $model->status) === Task::STATUS_COMPLETED
        && $model->status !== Task::STATUS_COMPLETED) {
        $completion->complete($model, $this->actor(), $request->validated(), $this->traceId());
    } else {
        $model->update($request->validated());
    }

    return redirect()->route('tasks.index')->with('success', 'Task updated successfully.');
}

So, at this point, you can understand the flow a bit more: precisely when the task is being marked as completed for the first time, by user request via the form, is when we mark it in our events, in the outbox event I just discussed earlier. And well, here also, in parallel, we send an email — but that's beside the point — and keep a trace. And we do this in TaskCompletion, and we do it both in update() and in store(): it might be that we also create a task marking it as completed right away, but it's the exact same logic as before; except that in this case we don't check for an existing task, because it doesn't exist — we are creating it for the first time, unlike update:

task-service/app/Http/Controllers/TaskController.php (web, store)

public function store(StoreTaskRequest $request, TaskCompletion $completion): RedirectResponse
{
    $validated = $request->validated();

    $task = Task::query()->create([
        'title' => $validated['title'],
        'user_id' => $this->user()->id,
        'status' => $validated['status'] ?? Task::STATUS_PENDING,
    ]);

    // Created already completed starts counting: the event goes out the same as
    // if the change had come from update.
    if ($task->status === Task::STATUS_COMPLETED) {
        $completion->complete($task, $this->actor(), [], $this->traceId());
    }

    return redirect()->route('tasks.index')->with('success', 'Task created successfully.');
}

Otherwise, notice that in tasks we don't have anything else. Here what we have is the email thing, which are simply jobs that live here in tasks; it has absolutely nothing weird: it's simply a normal framework queue and jobs task to send an email. We have SendTaskCompletedEmail to send the email — let's say — and also the class that defines the email we are going to send, where you can put it in HTML and everything else you want. In this case it is strictly HTML content:

task-service/app/Jobs/SendTaskCompletedEmail.php

class SendTaskCompletedEmail implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 3;
    public array $backoff = [5, 15];

    public function __construct(
        public readonly Task $task,
        public readonly array $actor,
    ) {}

    public function handle(): void
    {
        Mail::to($this->actor['email'])
            ->send(new TaskCompletedMail(
                task: $this->task,
                actor: $this->actor,
            ));
    }
}

// task-service/app/Mail/TaskCompletedMail.php
public function envelope(): Envelope
{
    return new Envelope(
        subject: "Task completed: {$this->task->title}",
    );
}

public function content(): Content
{
    return new Content(
        text: 'mails.task-completed',
    );
}

Otherwise you can see that we don't have anything else: the events config — we'll cover it again in a moment — the new outbox_events table managed here in the tasks one... and that's all on the producer side.

The cron (simulated in development) and the two processes

Ok, let's look at the flow. Remember what I mentioned before: this is a cron command that runs every minute, just as you can see. You can see it here in routes/console.php, and remember the command I mentioned before — php artisan schedule:work — which we start in tasks:

task-service/routes/console.php

Schedule::command(DispatchOutbox::class)->everyMinute()->withoutOverlapping();

The dispatch flow and the entry into billing

From here this thing called outbox:dispatch is triggered; internally it calls OutboxDispatcher, precisely this one we have here, which is the one that searches for events. But notice that it has much more code, and this method called deliverTo() is called. We saw it before and it is called right here in the OutboxDispatcher, which ultimately through the configuration side obtains the URL. Remember the configuration file I mentioned before: around there we have this URL, which is the controller that lives in billing — therefore let's see what it does — but I already showed you the flow. This is the entry into billing, from tasks:

packages/microservices-events/src/Outbox/OutboxDispatcher.php (deliverTo)

$delivery->forceFill(['attempts' => $delivery->attempts + 1])->save();

$body = (string) json_encode($this->manifest($event));
$signature = Signature::sign($body, (string) $subscriber['secret']);

// Without a circuit breaker in between: a failed delivery does not trigger
// panic, it comes back via available_at. Thus, a fallen receiver weighs as
// what it is: a delay, not a loss.
try {
    $response = Http::withHeaders([
        // The HMAC covers the raw body. Id, type and timestamp travel
        // in headers so the receiver verifies freshness and signature
        // without decomposing the JSON.
        'X-Event-Signature' => $signature,
        'X-Event-Id' => $event->event_id,
        'X-Event-Type' => $event->type,
        'X-Event-Timestamp' => (string) now()->getTimestamp(),
        'X-Request-Id' => $event->trace_id ?? '',
    ])
        ->acceptJson()
        ->timeout((int) config('events.timeout', 3))
        ->withBody($body, 'application/json')
        ->post((string) $subscriber['url']);
} catch (\Illuminate\Http\Client\ConnectionException $exception) {
    $failedDescription = 'Connection failed: '.substr($exception->getMessage(), 0, 200);
    $this->recordFailure($delivery, $name, $event, $failedDescription);

    return false;
}

if ($response->successful()) {
    $delivery->forceFill([
        'status' => 'delivered',
        'delivered_at' => now(),
        'last_error' => null,
    ])->save();

    return true;
}

$this->recordFailure($delivery, $name, $event,
    'HTTP '.$response->status().': '.substr($response->body() ?? '', 0, 256));

return false;

And on the other side, the receiver: here we have the API. You can see it is nicely /api/events and it's a POST. Therefore, what this controller does, in the end, is act as the entry into billing from tasks. Remember that when you see dispatch, these are the queues and jobs we have in the framework... well, it verifies all the trace is valid — as I tell you, you have to dive deep into the code — and places the job for the task right here, in this dispatch, in CreateInvoiceFromEvent. I think the name says it quite a bit: it's a job that is supposed to be triggered — the creation of the invoice for that task:

billing-service/routes/api.php

Route::post('/events', EventController::class)->middleware('events.verify');

// billing-service/app/Http/Controllers/Api/EventController.php
public function __invoke(Request $request): JsonResponse
{
    $eventId = (string) $request->attributes->get('event_id');
    $type = (string) $request->attributes->get('event_type');
    $payload = (array) $request->attributes->get('event_payload');

    Log::info('Event received', ['event_id' => $eventId, 'type' => $type]);

    if ($type === 'task.completed') {
        CreateInvoiceFromEvent::dispatch($eventId, $payload)->onQueue('invoices');
    }

    return new JsonResponse([
        'received' => true,
        'event_id' => $eventId,
    ], $type === 'task.completed' ? Response::HTTP_ACCEPTED : Response::HTTP_NO_CONTENT);
}

Otherwise, here you can see the Invoice model — which doesn't matter much: simply what we want to see is the flow. And the job, CreateInvoiceFromEvent, which what it does is create the invoice for the task. It checks if the user is valid; if obviously some data is missing an exception can occur — that the task doesn't exist or whatever — then that exception is caught, and there's the trace, of course. And that's really all. But it's quite a bit of code and quite complicated we could say... but that's it:

billing-service/app/Jobs/CreateInvoiceFromEvent.php

public function handle(): void
{
    $taskId = isset($this->payload['task_id']) ? (int) $this->payload['task_id'] : null;
    $userId = (int) ($this->payload['user_id'] ?? 0);
    $taskTitle = (string) ($this->payload['task_title'] ?? '');

    if ($userId < 1) {
        Log::warning('Event task.completed without user_id; no invoice', ['event_id' => $this->eventId]);

        return;
    }

    try {
        $invoice = Invoice::query()->create([
            'user_id' => $userId,
            'event_id' => $this->eventId,     // UNIQUE: the guarantee of a single invoice
            'task_id' => $taskId,
            'task_title' => $taskTitle !== '' ? $taskTitle : 'Task',
            'amount' => (float) config('events.charge_per_task', 10.0),
            'status' => Invoice::STATUS_PENDING,
        ]);
    } catch (UniqueConstraintViolationException) {
        // The same event already billed: it's the counterpart of at-least-once.
        Log::info('Invoice already existed for this event; not duplicating', [
            'event_id' => $this->eventId,
            'user_id' => $userId,
        ]);

        return;
    }

    Log::info('Invoice created from event', [
        'invoice_id' => $invoice->id,
        'event_id' => $this->eventId,
        'user_id' => $userId,
        'task_id' => $taskId,
    ]);
}

The databases and the moment of truth

In the database, for example, this is the tasks one, just as its name suggests: we have outbox_events and outbox_deliveries; and in the other one the invoices. Notice that for invoice I have five here. The idea is that when we create a task and mark it as completed, the invoice for that task should appear here. Remember that they are different services and databases, and this is a bit of the point.

Just as we saw before — and you cannot rewind the video, for God's sake — let's remember that TaskCompletion runs and with this builds the entire trace: when a task is marked as completed, whether when you create it or when you update it. So here, right away, from the form — according to what we saw before, the request part — I am going to mark this as completed. And what happens here is that it is not immediate, as you already saw: you have to wait in the worst case a minute, or however the cron we have activated works. Remember that you have to activate it here: I mean, the php artisan schedule:work command, remember it goes in tasks, which is the one in charge of reading this and executing every minute based on what we have configured. And also here you must have php artisan queue:work --queue=invoices, which is in charge of reading when it arrives at the events controller — in this case, to the job of creating the invoice — and executes it at some point in its life cycle, based on what we have here for queues and jobs, which are separate. And we already saw that in the book too.

And well, at some point in the life cycle, after a minute or so, we should see the invoice record in the bills service database.

Asynchronous Communication Between Microservices with RabbitMQ and Laravel Queue

As a microservices architecture evolves, background task management and application-to-application communication stop relying on the database and are delegated to a specialized message broker. A robust standard for this purpose is RabbitMQ.

1. What is RabbitMQ and why use it

RabbitMQ is an open-source messaging software designed to facilitate asynchronous, fast, and reliable communication between different systems and microservices. Unlike queues based on relational databases, a message broker optimizes concurrent processing and completely decouples publishing services from receiving ones.

To integrate this service into the Laravel ecosystem, an official queue management package is used (such as laravel-queue-rabbitmq), which allows connecting the application directly to the message server using a very simple configuration.

Let's install it in both the tasks and billing services:

$ composer require vladimir-yuldashev/laravel-queue-rabbitmq

2. Deploying the Container with Docker Compose

The cleanest and most efficient way to spin up RabbitMQ in a development environment is through containers using Docker Compose. At the root of the monorepo, the configuration file to orchestrate the service is defined:

docker-compose.yml

services:
  rabbitmq:
    image: rabbitmq:4-management
    container_name: demo-rabbitmq
    ports:
      - "5672:5672"
      - "15672:15672"
    volumes:
      - rabbitmq-data:/var/lib/rabbitmq
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
      interval: 10s
      timeout: 10s
      retries: 5

volumes:
  rabbitmq-data:

To launch the container, run the standard command from the terminal:

$ docker compose up -d

3. Configuring the Queue Driver in Laravel

One of the great advantages of using a framework like Laravel is transparency when changing drivers. Once the RabbitMQ package is installed and connection credentials are set in the .env file of each microservice (such as the task service and billing service), you just need to update the queue driver:

task-service/config/queue.php

billing-service/config/queue.php

'rabbitmq' => [
    'driver' => 'rabbitmq',
    'queue' => env('RABBITMQ_QUEUE', 'default'),
    'hosts' => [
        [
            'host' => env('RABBITMQ_HOST', '127.0.0.1'),
            'port' => env('RABBITMQ_PORT', 5672),
            'user' => env('RABBITMQ_USER', 'guest'),
            'password' => env('RABBITMQ_PASSWORD', 'guest'),
            'vhost' => env('RABBITMQ_VHOST', '/'),
        ],
    ],
    'options' => [],
    'worker' => env('RABBITMQ_WORKER', 'default'),
],

task-service/.env

billing-service/.env

QUEUE_CONNECTION=rabbitmq

With this single change, all job dispatching and processing logic (Jobs) is handled through RabbitMQ without needing to modify the asynchronous tasks code.

4. Queue Processing and Service-to-Service Communication

Once the environment is configured, asynchronous event processing operates in a fully integrated manner. For example, upon marking a task as completed in the corresponding service, an event is dispatched to the queue so that the Billing Service automatically generates the associated invoice in parallel without blocking the user, using the same commands we saw before.

Conclusion

Migrating database queues to a professional broker like RabbitMQ drastically optimizes scalability and resilience in microservice architectures. This ensures smooth, secure asynchronous communication prepared for high-concurrency production environments.

Project source code:

https://github.com/libredesarrollo/course-book-laravel-microservicios-13

A guide to microservices with Laravel. Learn about SSO, JWT, the Circuit Breaker pattern, rate limiting, queues and jobs, and traceability using Correlation IDs—step by step, from scratch—to connect three sample services.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.