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

Php Datadogstatsd Laravel Package

datadog/php-datadogstatsd

DogStatsD client for PHP from Datadog. Send metrics, events, and service checks to the Datadog Agent via UDP or UDS, with support for tags, sampling, buffering, and namespacing. Useful for instrumenting PHP apps and services.

View on GitHub
Deep Wiki
Context7
## Product Decisions This Supports
- **Observability & Monitoring Roadmap**:
  - **Defensive Instrumentation**: Introduces **customizable error handling for socket failures**, enabling teams to implement **retry logic, fallback mechanisms (e.g., HTTP submission), or dead-letter queues** for critical metrics. Directly addresses **metric integrity** in unreliable networks, aligning with **SLO-based reliability** and **postmortem prevention**.
  - **Extensibility for Edge Cases**: Supports **granular control** over metric submission failures, allowing integration with **circuit breakers, alerting systems, or distributed tracing** (e.g., correlating socket errors with APM traces in Datadog).
  - **Compliance & Audit Trails**: Ensures **structured error logging** for metrics, critical for industries like **finance, healthcare, or regulated SaaS** where dropped data could violate compliance (e.g., GDPR, PCI-DSS).

- **Build vs. Buy**:
  - **Cost-Effective Resilience**: Eliminates the need to **build custom UDP retry logic** or **maintain forked StatsD clients**, reducing technical debt. The package now offers **enterprise-grade fault tolerance** out-of-the-box for PHP services.
  - **Unified Observability Stack**: Strengthens the case for **standardizing on Datadog** by providing **native error recovery** within the Laravel ecosystem, reducing friction for teams evaluating observability tools.

- **Use Cases**:
  - **High-Stakes PHP Services**:
    - **Financial Transactions**: Prevents **false negatives** in fraud detection or payment processing by ensuring metric submission (e.g., `transaction.failed`) persists even during network partitions.
    - **Real-Time Systems**: Critical for **IoT pipelines, gaming backends, or ad-tech** where UDP drops could trigger cascading failures.
    - **CLI Workers & Cron Jobs**: Mitigates **intermittent UDP failures** in batch processing (e.g., data ingestion, report generation).
  - **Multi-Region/Edge Deployments**:
    - **Hybrid Cloud**: Handles **firewall-induced UDP blockages** or **inter-AZ latency** in AWS/GCP deployments.
    - **Global CDNs**: Ensures metrics from **edge locations** (e.g., Cloudflare Workers) reach Datadog despite unstable connectivity.
  - **Observability-Driven Development**:
    - **Feature Flags & Canary Releases**: Allows **custom error handlers** to log metric submission failures as **feature-flagged incidents** (e.g., "Canary X failed to report metrics").
    - **Chaos Engineering**: Enables **controlled failure testing** (e.g., simulating UDP drops to validate resilience).

- **Strategic Leverage**:
  - **Risk Mitigation Framework**:
    - Integrates with **Datadog’s Service Level Objectives (SLOs)** by ensuring **metric completeness** even during outages.
    - **Bridges gaps** between Datadog and internal monitoring (e.g., forward socket errors to **Prometheus Pushgateway** or **Elasticsearch**).
  - **Developer Experience (DX)**:
    - **Zero-Cost Resilience**: Error handling is **opt-in**, reducing cognitive load for teams not needing advanced features.
    - **Consistent Patterns**: Encourages **reusable error-handling logic** across microservices (e.g., shared `SocketErrorHandler` library).

---

## When to Consider This Package
- **Adopt If**:
  - Your PHP services **cannot tolerate metric drops** due to **business, compliance, or reliability requirements** (e.g., **financial settlements, healthcare diagnostics, or real-time bidding**).
  - You operate in **unstable network environments** where UDP is **not inherently reliable**, such as:
    - **Multi-cloud or hybrid deployments** (e.g., on-prem + AWS).
    - **Edge computing** (e.g., serverless functions, CDN workers).
    - **Bursty or high-volume workloads** (e.g., **CLI batch jobs, event-driven architectures**).
  - You need **fine-grained control over metric submission failures**, including:
    - **Custom retry logic** (e.g., exponential backoff for socket reconnection).
    - **Fallback mechanisms** (e.g., buffering metrics to disk/Redis and flushing later).
    - **Alerting or logging** socket errors as **separate observability signals**.
  - Your team uses **Datadog’s advanced features** (e.g., **service maps, APM, or logs**) and wants to **correlate socket errors with traces/metrics**.
  - You’re **investing in resilience engineering** and want to **prevent observability blind spots** (e.g., "Why did this service stop reporting metrics?").

- **Look Elsewhere If**:
  - Your environment **guarantees stable UDP connectivity** (e.g., **dedicated private network, no firewalls, or low-latency VPC**): The overhead of error handling may not justify the benefits.
  - You prioritize **simplicity over resilience** and are **not monitoring critical systems** (e.g., **internal tools, prototypes, or low-traffic APIs**).
  - Your **compliance requirements mandate synchronous, acknowledged metric delivery** (e.g., **blockchain validation, legal hold data**), making UDP fundamentally unsuitable regardless of error handling.
  - You’re **not using Datadog** and lack the infrastructure to **handle custom error recovery** (e.g., no fallback logging, alerting, or distributed tracing).
  - Your team **prefers HTTP-based metric submission** (e.g., via Datadog Agent) and sees UDP as **inherently risky** without additional layers (e.g., a service mesh).

---

## How to Pitch It (Stakeholders)
**For Executives**:
*"This update **transforms our PHP observability from ‘best-effort’ to ‘mission-critical’** by adding **customizable error handling for metric submission failures**. For our **high-stakes services**—like payments, real-time analytics, or global edge workloads—it ensures we **never miss a metric due to a network blip**, directly protecting our **revenue, compliance, and customer trust**.

**Why It Matters**:
- **Prevents Silent Failures**: No more wondering why a service ‘stopped reporting’—errors are now **visible and actionable**.
- **Future-Proofs Resilience**: Aligns with our **SLO-driven reliability goals** and **chaos engineering** initiatives.
- **Low Risk, High Reward**: A **backward-compatible** upgrade that **only adds value where needed** (opt-in), with **minimal performance impact**.

**Ask**: Should we **enable this for our top 10% most critical PHP services** (e.g., checkout, fraud detection) as a **Q4 reliability initiative**? The cost is **near-zero**, but the upside is **eliminating a class of production incidents**."*

---

**For Engineering**:
*"The **1.7.1 release introduces **custom socket error handlers**, which is a **game-changer for resilient observability**. Here’s how to leverage it:

### **Key Features**
1. **No More Silent Metric Drops**:
   - Define a callback to **log, alert, or retry** when UDP submission fails:
     ```php
     use Cosmastech\DogStatsD\SocketErrorHandler;
     SocketErrorHandler::set(function ($error) {
         // Option 1: Log to Datadog Errors
         \Datadog\Log::error("DogStatsD socket failed: " . $error->getMessage());

         // Option 2: Retry with exponential backoff
         if ($error instanceof \RuntimeException) {
             retry()->times(3)->then(fn() => sendMetrics());
         }

         // Option 3: Fallback to HTTP
         if ($error->getCode() === 101) { // EHOSTUNREACH
             sendMetricsViaHttp();
         }
     });
     ```
2. **Built for Edge Cases**:
   - **Bursty Workloads**: CLI jobs or cron tasks won’t lose metrics during **network congestion**.
   - **Multi-Region**: Handles **inter-AZ or cross-cloud UDP failures** (e.g., GCP → AWS).
   - **Hybrid Cloud**: Works behind **firewalls or proxies** that block UDP.

### **Implementation Plan**
1. **Prioritize High-Risk Services**:
   - Start with services where **metric drops would cause alerts** (e.g., `orders.failed`, `payments.processed`).
   - Example: **Payment processing API** → Add error handler to log socket failures as **Datadog Errors** with service context.

2. **Test Under Failure**:
   - Simulate UDP drops (e.g., `iptables -A OUTPUT -p udp -j DROP`) and verify your handler works.
   - Use **Datadog’s Synthetics** to monitor metric submission reliability.

3. **Document Patterns**:
   - Create a **shared runbook snippet** for teams:
     ```markdown
     ## Handling DogStatsD Socket Failures
     **When**: UDP submission fails (e.g., network partition).
     **Action**:
     1. Log error to Datadog Errors with tags `{service: "checkout", component: "metrics"}`.
     2. Retry once with 1s delay.
     3. Fallback to HTTP if UDP is permanently blocked.
     **Example**:
     ```php
     SocketErrorHandler::set(function ($error) {
         \Datadog\Log::error
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky