Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Health Check Bundle Laravel Package

ekreative/health-check-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require ekreative/health-check-bundle
    
  2. Register Bundle in config/app.php (Laravel 5.5+) or AppKernel.php (Symfony):
    Ekreative\HealthCheckBundle\EkreativeHealthCheckBundle::class,
    
  3. Add Routing in routes/web.php (Laravel) or config/routes.yaml (Symfony):
    ekreative_health_check:
        resource: "@EkreativeHealthCheckBundle/Resources/config/routes.xml"
    
  4. Disable Security for /healthcheck in config/security.php (Laravel) or config/packages/security.yaml (Symfony):
    firewalls:
        healthcheck:
            pattern: ^/healthcheck
            security: false
    
  5. First Use Case: Visit /healthcheck to verify the endpoint returns a 200 OK with JSON response:
    {
        "status": "ok",
        "database": true
    }
    

Implementation Patterns

Core Workflows

  1. Basic Health Check:

    • Out-of-the-box checks Doctrine’s default connection. Extendable for other services.
    • Example response:
      { "status": "ok", "database": true }
      
  2. Multi-Database Checks:

    • Configure additional Doctrine connections in config/packages/ekreative_health_check.yaml:
      ekreative_health_check:
          doctrine:
              - 'default'
              - 'read_replica'
      
    • Response includes all configured connections:
      { "status": "ok", "database": { "default": true, "read_replica": false } }
      
  3. Custom Checks:

    • Extend the bundle by creating a custom checker service:
      // src/Service/CustomHealthChecker.php
      namespace App\Service;
      
      use Ekreative\HealthCheckBundle\Checker\CheckerInterface;
      
      class CustomHealthChecker implements CheckerInterface
      {
          public function check(): bool
          {
              // Your logic (e.g., API call, queue check)
              return true;
          }
      
          public function getName(): string
          {
              return 'custom_service';
          }
      }
      
    • Register the service in config/services.yaml:
      services:
          App\Service\CustomHealthChecker:
              tags: ['ekreative.health_check.checker']
      
  4. Integration with Monitoring:

    • Use the endpoint in tools like Prometheus, Datadog, or UptimeRobot for uptime monitoring.
    • Example Prometheus scrape config:
      - job_name: 'laravel'
        static_configs:
          - targets: ['your-app.com:80/healthcheck']
      
  5. API Gateway/Load Balancer Health:

    • Configure /healthcheck as a probe endpoint in AWS ALB, Nginx, or Kubernetes:
      location /healthcheck {
          proxy_pass http://backend;
          health_check;
      }
      

Gotchas and Tips

Pitfalls

  1. Security Misconfiguration:

    • Forgetting to disable security for /healthcheck exposes the endpoint to unauthorized access.
    • Fix: Always explicitly set security: false for the healthcheck firewall.
  2. Connection Failures:

    • If Doctrine connections fail silently, the health check may return false without context.
    • Debug: Check Laravel/Symfony logs (storage/logs/laravel.log) for connection errors.
  3. Caching Issues:

    • Some load balancers cache health check responses. Ensure the endpoint is non-cacheable:
      // In a middleware or controller
      return response()->json($data)->header('Cache-Control', 'no-cache');
      
  4. Custom Checker Errors:

    • If a custom checker throws an exception, the health check may fail silently.
    • Best Practice: Wrap logic in try-catch and log errors:
      public function check(): bool {
          try {
              // Risky logic
              return true;
          } catch (\Exception $e) {
              \Log::error('Health check failed: ' . $e->getMessage());
              return false;
          }
      }
      

Tips

  1. Response Customization:

    • Override the default JSON response by extending the controller:
      // src/Http/Controllers/HealthCheckController.php
      namespace App\Http\Controllers;
      
      use Ekreative\HealthCheckBundle\Controller\HealthCheckController as BaseController;
      
      class HealthCheckController extends BaseController
      {
          protected function getResponseData(): array
          {
              $data = parent::getResponseData();
              $data['version'] = '1.0.0'; // Add custom fields
              return $data;
          }
      }
      
  2. Performance Optimization:

    • Run checks in parallel for faster responses:
      // In a custom checker
      public function check(): bool {
          $promises = [];
          foreach ($this->connections as $connection) {
              $promises[] = $this->checkConnection($connection);
          }
          return collect($promises)->every(fn ($result) => $result);
      }
      
  3. Environment-Specific Checks:

    • Disable checks in non-production environments:
      # config/packages/ekreative_health_check.yaml
      enabled: '%env(bool:ENABLE_HEALTH_CHECKS)%'
      
  4. Testing:

    • Mock the health check in PHPUnit:
      $this->app->instance(
          Ekreative\HealthCheckBundle\Checker\CheckerInterface::class,
          $this->createMock(Ekreative\HealthCheckBundle\Checker\CheckerInterface::class)
      );
      
    • Verify responses with:
      $response = $this->get('/healthcheck');
      $response->assertStatus(200);
      $response->assertJson(['status' => 'ok']);
      
  5. Logging:

    • Log health check results for observability:
      \Log::info('Health check result', [
          'status' => $this->check(),
          'checker' => $this->getName(),
      ]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle