techlist.io

Datadog

200 posts

www.datadoghq.com/blog/engineering

Filter by tag

Datadog2018-04-241 min readCurated summary

Using Datadog APM to improve the performance of Homebrew | Datadog

Datadog announces that Gartner named it a Leader in the 2026 Magic Quadrant for Observability Platforms. The provided content is primarily the website’s navigation menu and does not include the blog article’s substantive discussion, methodology, or supporting evidence. ## Gartner Recognition - Datadog highlights its position as a Leader in Gartner’s Magic Quadrant for Observability Platforms. - The linked resource appears to support or explain the recognition. ## Datadog’s Observability Portfolio The navigation indicates that Datadog’s platform spans: - **Infrastructure:** infrastructure, container, network, serverless, GPU, storage, and cloud-cost monitoring. - **Applications:** APM, profiling, dynamic instrumentation, and service monitoring. - **Logs and data:** log management, database monitoring, data-stream monitoring, and observability pipelines. - **Security:** cloud security, SIEM, vulnerability management, workload protection, and code security. - **Digital experience:** real-user monitoring, session replay, synthetic monitoring, product analytics, and error tracking. - **Software delivery and service management:** CI visibility, testing, incident response, SLOs, workflow automation, and internal developer portals. - **AI capabilities:** agent observability, AI integrations, investigation agents, and GPU monitoring. The supplied excerpt does not provide enough article text to summarize Datadog’s specific strengths, Gartner’s evaluation criteria, or the company’s evidence for being named a Leader.

Datadog2018-04-162 min readCurated summary

Cgo and Python

Embedding Python in Go lets applications gradually migrate from Python, reuse existing libraries, and load scripts dynamically without recompiling. Datadog uses this approach in its Go-based Agent so checks can remain in Python while the core application moves to Go. The key is combining cgo with a Go-friendly wrapper around CPython’s C API. ## Why Embed Python in Go? - Supports incremental migration from an existing Python codebase. - Reuses mature Python libraries without reimplementing them in Go. - Enables runtime loading and execution of custom or updated Python scripts. - This dynamic extensibility is especially important for Datadog checks. ## Introducing cgo - CPython exposes a C API, while Go requires a Foreign Function Interface to call C code. - cgo provides that integration while preserving the normal `go build` workflow. - A C preamble placed immediately before `import "C"` can include headers and C code. - The pseudo-package `C` exposes C constants, functions, and types to Go. - `go build -x` reveals how cgo generates intermediate C and Go files, compiles them, and links the final binary. ## Initializing the CPython Interpreter - A Go program must initialize Python with `Py_Initialize()` before executing Python code. - It should shut down the interpreter with `Py_Finalize()` when finished. - `Py_GetVersion()` demonstrates retrieving Python information through the C API. - `#cgo` directives can use `pkg-config` to locate Python development headers and libraries, such as `python-2.7`. - The examples use Python 2, but the same approach largely applies to Python 3. ## Using a Go Wrapper - Direct cgo interaction is mostly boilerplate, so Datadog uses the `go-python` library. - The wrapper exposes operations such as: - `python.Initialize()` - `python.PyRun_SimpleString(...)` - `python.Finalize()` - This hides cgo details and makes embedded Python code look more idiomatic from Go. ## Importing and Calling Python Code - A Python module can be imported with `PyImport_ImportModule`. - Go retrieves a function using `GetAttrString`. - The function is invoked through the Python API, passing empty tuple and dictionary objects even when it accepts no arguments. - The Go code must check for failures when importing modules or locating functions. - A simple `foo.py` module containing a `hello()` function can therefore be loaded and executed from disk. Embedding CPython through cgo provides a practical bridge between Go and Python. A wrapper such as `go-python` makes the integration easier to maintain, while allowing applications like the Datadog Agent to combine a Go core with dynamically executed Python components.

Datadog2018-04-161 min readCurated summary

Cgo and Python | Datadog

The provided content does not include the blog post itself. It contains Datadog’s navigation menu and a link to an engineering article titled “CGO and Python,” but no article text from which to produce a reliable summary. Please provide the post’s body or a readable URL extract, and I can summarize it in the requested format.

Datadog2018-03-232 min readCurated summary

What product designers can learn from explanatory journalism

Explanatory journalism offers product designers a useful model: prioritize important context over the latest information, prevent context from being lost, and explain decisions clearly to different audiences. The author argues that thorough research and documentation make design communication more concise and persuasive. A well-maintained “papertrail” becomes the foundation for better decisions and explanations. ## Favor the Important Over the New - Constantly updating feeds encourage people to value recent information over significant information. - Designers face the same bias when reacting to the latest: - Support ticket - Meeting summary - Customer call - Feedback should be collected in one place and labeled by source so it can be weighted appropriately. - Tracking how many customers or teams request something helps identify common needs and prioritize them. ## Prevent Context Collapse - Sharing tools make it easy to distribute mockups and updates, but recipients may lack the background needed to evaluate them properly. - Product decisions often draw on many sources: - Customer support conversations - Product managers’ customer meetings - Sales requirements - Design research interviews - Executive goals - Designers should assemble this context over time and preserve it in one accessible location. - During reviews, the designer must explain not only the proposed solution but also how it responds to—or intentionally excludes—the concerns of each audience. ## Use the Available Space - Digital publishing and podcasts are not constrained by the same space limitations as traditional media, making background and context easier to provide. - The author describes design work as two phases: - **Expansion:** Gather research, precedent, data, requirements, and evidence. - **Contraction:** Distill that material into concise explanations and decisions. - A thorough, organized research record makes short summaries, presentations, and conversations more accurate and effective. - Links from concise explanations to the underlying research preserve context without overwhelming the main narrative. ## Build and Maintain a Design Papertrail - Documentation benefits the designer even when nobody else reads every detail. - A papertrail should be: - Created during the research process - Kept up to date - Revisited regularly - Used as the canonical source for design decisions - The work focuses primarily on product usability, workflows, and interaction design, while product managers may focus more on pricing, prioritization, timelines, and business considerations. The practical recommendation is to document broadly, organize the evidence, and explain selectively. Designers who maintain strong context will make better decisions and communicate them more effectively.

Datadog2017-09-203 min readCurated summary

Secure (and usable) multi-AWS account IAM setup | Datadog

The post presents a defense-in-depth approach to securing AWS accounts with IAM. Its central recommendation is to minimize long-lived credentials and broad permissions by combining strong authentication, role-based access, least privilege, and continuous auditing. Secure account governance is treated as an ongoing operational process rather than a one-time configuration. ## Protect the Root User - Use the root user only for tasks that cannot be performed through IAM. - Enable multi-factor authentication (MFA), preferably with a hardware security key. - Avoid creating root access keys. - Store root credentials securely and monitor for any root-user activity. ## Use Federated, Role-Based Access - Prefer AWS IAM Identity Center or an external identity provider for human access. - Grant users access through groups and roles instead of individual permissions. - Use short-lived role credentials rather than permanent IAM user access keys. - Require separate roles for administrative, development, production, and read-only work. ## Apply Least Privilege - Start with narrowly scoped permissions and expand them only when necessary. - Restrict actions by resource, account, region, and relevant condition keys. - Avoid wildcard permissions such as `Action: "*"` and `Resource: "*"`. - Use IAM Access Analyzer and CloudTrail activity to identify unused or excessive permissions. - Add permission boundaries or organization-level Service Control Policies when teams need guardrails around delegated administration. ## Secure Workloads and Automation - Assign IAM roles directly to EC2 instances, Lambda functions, containers, and other workloads. - Do not embed access keys in source code, configuration files, or deployment artifacts. - Store unavoidable secrets in services such as AWS Secrets Manager or Systems Manager Parameter Store. - Rotate and revoke credentials promptly when they are exposed or no longer required. ## Monitor and Audit IAM - Enable CloudTrail across accounts and regions, with logs protected from modification. - Alert on suspicious activity, including root-user use, policy changes, disabled logging, and unusual access-key behavior. - Regularly review users, groups, roles, policies, and unused credentials. - Use AWS Config, Security Hub, or equivalent controls to check compliance with account-security requirements. ## Centralize Governance - Manage multiple AWS accounts through AWS Organizations. - Keep production and sensitive workloads isolated from development accounts. - Apply Service Control Policies to prevent high-risk actions, even for administrators. - Establish a controlled emergency or “break-glass” access process with strong monitoring. The practical recommendation is to combine MFA, centralized identity, temporary role credentials, narrowly scoped permissions, and continuous auditing. No individual IAM setting is sufficient on its own; security comes from layering preventive controls with detection and response.

Datadog2017-09-203 min readCurated summary

Secure (and usable) multi-AWS account IAM setup

Managing multiple AWS accounts increases billing, compliance, and operational complexity, but it provides valuable security boundaries between workloads. The post proposes a centralized IAM design in which users exist in only one account, receive minimal default permissions, and temporarily assume narrowly scoped roles in target accounts. MFA and short-lived credentials further limit the impact of compromised credentials, although the approach is constrained to roughly ten accounts by IAM group limitations. ## Why Use Multiple AWS Accounts? - Accounts isolate workloads at several levels: - **Network:** VPCs are separate unless explicitly peered. - **API access:** A compromised account cannot access others without delegated roles. - **Compute and billing:** Per-account spending limits, billing alerts, and CloudTrail monitoring can contain or reveal abuse such as cryptocurrency mining. - The main challenge is gaining these security benefits without creating unmanageable administrative overhead. - The proposed pattern is better suited to production environments than development setups where every developer may have a separate account. - Current IAM group limitations restrict the design to approximately ten accounts. ## Centralized IAM User Management - Each IAM user should exist in only one account. - Centralizing users makes onboarding, offboarding, password policies, and auditing easier. - Other accounts can be monitored for unexpected IAM user creation, which should generally never occur. - Users receive only the permissions needed to manage their own authentication settings. ## Why Use IAM Instead of SSO? - SSO would centralize authentication through an existing identity provider. - However, the post argues that SSO can limit the ability to apply MFA protection precisely to privileged operations. - Since MFA is central to the proposed privilege-escalation model, standalone IAM users are retained despite their administrative drawbacks. ## Minimal Default Permissions By default, users should be able to: - View their own IAM record. - Change their console password. - Create, update, or delete their own API credentials. - Create their own MFA device. They should have no meaningful access to other AWS APIs. This limits the blast radius of stolen usernames, passwords, or API keys: without the user’s MFA device, an attacker can generally do little more than inspect the compromised user’s record. ## Temporary Privilege Through Role Assumption - Users perform privileged work by calling `sts:AssumeRole` in the target account. - Assuming a role provides temporary credentials and a session token. - Credentials have a short lifetime, normally no more than one hour by default. - This resembles the Unix `sudo` model: users begin with restricted permissions and explicitly elevate privileges when necessary. ## MFA-Protected Privilege Escalation A role assumption should succeed only when both conditions are met: - The user has an active MFA device and can authenticate with it. - The user belongs to a group authorized to assume the requested role. MFA does not eliminate compromise risk, but it makes stolen API credentials substantially less useful and limits the damage they can cause without the corresponding MFA device. ## Privileges Grouped by Operational Topic - Administrative capabilities are divided into roles based on responsibility rather than assigning broad account-wide permissions. - Example roles include: - A **VPC role** for network configuration. - An **EC2 role** for instance management. - An **S3 role** for storage administration. - Users can then be mapped to groups and roles according to their job responsibilities, making permissions easier to understand and maintain. ## Practical Recommendation Use multiple AWS accounts as deliberate security boundaries, but centralize IAM users, keep their baseline permissions minimal, require MFA for role assumption, and grant temporary, topic-specific roles. This provides strong isolation while keeping privilege management manageable, particularly for production environments with a limited number of accounts.

Datadog2017-09-061 min readCurated summary

Robust statistical distances for machine learning | Datadog

The supplied text does not include the blog post itself; it is largely Datadog’s navigation menu. The only identifiable article is **“Robust Statistical Distances for Machine Learning,”** so a detailed, source-grounded summary is not possible without the article body. ## Article Focus - The post appears to address statistical distances used to compare probability distributions in machine-learning systems. - Its focus is likely making these comparisons more **robust to outliers, noisy observations, and distribution shifts**. - Such distances can support tasks including anomaly detection, model monitoring, data-drift detection, and evaluating generated data. ## Why Robustness Matters - Conventional distance measures may be disproportionately influenced by extreme values. - Outliers can make two otherwise similar datasets appear substantially different. - A robust distance should distinguish meaningful distribution changes from isolated or corrupted observations. ## Practical Implication The article’s central recommendation is presumably to choose statistical-distance methods based not only on mathematical properties, but also on their resistance to noise and outliers. Please provide the actual article text for a complete, section-by-section summary with the specific techniques and conclusions.

Datadog2017-09-063 min readCurated summary

Robust statistical distances for machine learning

Statistical distances provide quantitative ways to measure how similar or different data distributions are, complementing visual tools such as histograms and Q-Q plots. The post compares the Kolmogorov-Smirnov, Earth Mover’s, and Cramér-von Mises distances, showing that each responds differently to local changes, long tails, and shifts in distribution. No single metric is universally best; the appropriate choice depends on which differences matter most. ## Visual Inspection and Q-Q Plots - Histograms offer a quick comparison of: - Minimum and maximum values - Center or average - Spread and overall shape - Q-Q plots sort both datasets and plot corresponding values against one another. - Points close to the first bisector indicate that the datasets likely come from similarly shaped distributions. - Visual methods are useful heuristics but do not provide a precise quantitative distance. ## Kolmogorov-Smirnov Distance - The KS distance compares empirical cumulative distribution functions (CDFs). - It is the largest absolute difference between the two CDFs at any point. - It is a true metric: - It is nonnegative. - It is zero only for identical distributions. - It is symmetric. - It satisfies the triangle inequality. - The distance is bounded between 0 and 1. - This makes it convenient for determining whether distributions are similar, but less useful for measuring how far apart very different distributions are. - For normal distributions with equal standard deviations and increasingly separated means, KS quickly levels off rather than growing proportionally. ## Earth Mover’s Distance - Earth Mover’s Distance (EMD), or the first Wasserstein distance, measures the minimum work required to transform one distribution into another. - “Work” is the amount of mass moved multiplied by the distance it travels. - EMD is equivalent to the area between the two empirical CDFs. - It is particularly useful for distributions with long or significant tails because distant mass contributes substantially to the result. - Unlike KS, EMD is unbounded and can grow with the physical separation between distributions. ## Cramér-von Mises Distance - The Cramér-von Mises (CM) distance sums the squared differences between empirical CDFs and takes the square root. - Its relationship to EMD resembles the relationship between L2 and L1 norms. - CM is less sensitive to isolated local changes than KS but more sensitive than EMD. - For normal distributions with separated means: - EMD grows linearly with the separation. - KS rapidly reaches a plateau. - CM grows approximately like the square root of the separation. ## Sensitivity to Distribution Changes - KS focuses on the maximum CDF difference, making it highly sensitive to local deformations. - EMD averages absolute CDF differences, so localized changes may have little effect. - CM provides a compromise, detecting local changes without reacting as strongly as KS. - In examples involving shifted or localized probability mass: - KS can increase dramatically from a small local deformation. - EMD may barely change. - CM usually shows a moderate increase. - Conversely, changes in distant high-percentile regions may have little effect on KS while producing much larger changes in EMD and CM. Choose the distance according to the type of distributional difference you need to detect: KS for maximum local deviation, EMD for overall displacement and long tails, and CM for a balanced sensitivity to both global and local changes.

Datadog2017-08-231 min readCurated summary

Scaling support with Vagrant and Terraform | Datadog

The provided content does not include the blog post itself. It consists primarily of Datadog’s navigation menu and a promotional banner announcing its Gartner recognition, while the linked page suggests an article about scaling support with Vagrant and Terraform. ### Visible Content - Datadog announces that it was named a **Leader in the Gartner Magic Quadrant for Observability Platforms**. - The page navigation lists products across: - Infrastructure and application monitoring - Logs, security, and digital experience - CI/CD, service management, and AI - The URL references an engineering post titled **“Scaling Support With Vagrant and Terraform,”** but no article text is present. A meaningful technical summary requires the article body or a complete extract of the post.

Datadog2017-08-233 min readCurated summary

Scaling support with Vagrant and Terraform

Datadog’s Solutions Team uses reproducible virtual environments to investigate customer issues across diverse operating systems, kernels, and integrations. Vagrant simplifies local VM creation, while provisioning scripts eliminate repeated installation and configuration work. Terraform extends the same approach to shared AWS environments, enabling teams to provision, preserve, and collaborate on sandboxes quickly. ## Reproducing Customer Environments with Vagrant - Containers are useful, but virtual machines are better when reproducing specific operating systems, kernels, orchestrators, or complex infrastructure. - Vagrant provides a simple workflow: - `vagrant init` - `vagrant up` - `vagrant ssh` - The main challenge is not creating a VM, but installing and configuring the technologies needed to match a customer’s environment. - With more than 200 integrations, engineers cannot be experts in every technology they may need to troubleshoot. ## Standardizing Setup with Provisioning Scripts - Vagrant provisioning supports tools such as Chef, Puppet, Ansible, and ordinary shell scripts. - Datadog stores reusable reproduction environments in a shared GitHub repository. - Each sandbox includes: - A `Vagrantfile` - A `setup.sh` provisioning script - A `data` directory for configuration files and supporting scripts - A `README.md` with usage information - Engineer-specific values, such as hostnames and tags, are kept in a local `.sandbox.conf.sh` file. - Once a sandbox exists, an engineer can run `vagrant up` and begin reproducing the customer issue within minutes. - The directory hierarchy organizes sandboxes by operating system, version or provider, and technology—for example, Ubuntu Xenial with Kafka. ## Sharing Remote Environments with Terraform - Terraform provides similar infrastructure management for remote cloud instances, including AWS EC2. - The team reuses the same `setup.sh` and `data` files for both Vagrant and Terraform, avoiding duplicate configuration work. - Each sandbox adds a `.tf` file that: - Creates an EC2 instance - Copies required data files - Executes the provisioning script remotely - A shared Terraform module handles common infrastructure tasks, while a `tf.example` file helps engineers create new configurations. - This preserves the same repository structure and workflow while extending sandboxes from local VMs to remote environments. ## Benefits for Team Collaboration - Remote sandboxes can remain available without consuming engineers’ local RAM. - Proper network security allows teammates to access and share environments. - Engineers can reproduce previously configured integrations during live customer interactions. - Investigations can continue across time zones, allowing teams to hand off urgent issues without rebuilding the environment. The overall recommendation is to treat reproduction environments as reusable infrastructure: encode installation and configuration steps once, store them in version control, and use Vagrant for local testing and Terraform for persistent, shared cloud sandboxes.

Datadog2017-08-153 min readCurated summary

Improving cloud security visibility with ChatOps

Datadog built a largely serverless AWS security monitoring pipeline to detect suspicious API activity across more than 15 AWS accounts. Rather than process every CloudTrail event equally, it categorizes actions as log, notify, or alert, reducing false positives while preserving broad visibility. The system centralizes events, batches activity, and uses automated workflows to verify engineers’ actions or escalate potential compromises. ## The Security Monitoring Challenge - Datadog manages extensive AWS infrastructure across multiple accounts and nearly 200 geographically distributed engineers. - Every console or CLI operation generates an AWS API call, creating a high-volume CloudTrail data stream. - The monitoring system must detect malicious activity while also catching accidental exposure caused by configuration mistakes. - Processing every event manually would require an expensive, constantly staffed Security Operations Center. ## Prioritizing Relevant API Calls - Datadog maintains a focused list of security-relevant AWS API calls and assigns each to one of three categories: - **Log:** Lower-risk events retained for investigation, such as `CreateGroup` or `UpdateUser`. - **Notify:** Events that require the initiating engineer to confirm their identity and intent, such as `CreateUser` or `PutUserPolicy`. - **Alert:** Rare, dangerous, or clearly misconfigured actions sent directly to the security team. - A representative alert is `AuthorizeSecurityGroupIngress` with `0.0.0.0/0`, which exposes an EC2 security group to the entire Internet. - User verification reduces false positives and helps identify compromised AWS credentials. ## Cross-Account Event Pipeline - CloudTrail records API activity in each AWS account. - CloudWatch Event Rules filter for the selected API calls and publish matching events to SNS. - SNS forwards events across accounts to an SQS queue in a dedicated security AWS account. - Centralization is necessary because CloudWatch could not directly send events cross-account to SQS. - The queue also supports batching, which is important when Terraform generates many AWS changes in a short period. - A CloudWatch rule triggers a Lambda function every two minutes to drain the SQS queue and forward events to the security orchestration layer. ## Automated Decision-Making with Komand - Datadog uses Komand, a security orchestration and automation platform, to construct workflows from built-in and custom plugins. - A custom decision plugin evaluates: - The calling user - The event’s age - Request parameters and their content - Other contextual details - Based on the analysis, the workflow silently logs the event, notifies the engineer, or pages the security team through PagerDuty. ## Engineer Verification and Escalation - For notification-level events, the engineer receives an interactive Slack message containing API call details. - Confirming the action triggers a Duo push for second-factor identity verification. - If the engineer denies the action or fails to respond promptly, the workflow alerts the security team. - Komand coordinates the Slack, Duo, PagerDuty, and custom integration logic in one centralized workflow. ## Visibility and Continuous Improvement - Every workflow execution is logged and sent to Elasticsearch. - The resulting data helps Datadog visualize security events, measure detection effectiveness, identify behavioral trends, and improve alerting. - The pipeline is designed to provide actionable security intelligence without overwhelming engineers or security personnel. Datadog’s approach combines selective event filtering, cross-account centralization, batching, and automated identity verification. Organizations facing similar AWS-scale monitoring challenges can use the same principles to reduce alert fatigue while maintaining strong detection and response capabilities.

Datadog2017-08-152 min readCurated summary

Improving cloud security visibility with ChatOps | Datadog

Datadog announces that it was named a Leader in the 2026 Gartner® Magic Quadrant™ for Observability Platforms. The provided content does not include the blog post’s body or Gartner’s evaluation details; it mainly contains Datadog’s navigation menu and product links. ## Announcement - Datadog highlights its recognition as a Leader in Gartner’s 2026 Observability Platforms Magic Quadrant. - The linked resource appears to be a Gartner-related announcement rather than a technical deep dive. ## Datadog’s Product Scope The navigation reflects a broad observability and operations platform covering: - Infrastructure monitoring, metrics, containers, Kubernetes, networks, serverless systems, and cloud costs - Application performance monitoring, profiling, dynamic instrumentation, and agent observability - Database, data-stream, jobs, and quality monitoring - Log management, sensitive-data scanning, audit trails, and observability pipelines - Security capabilities including cloud security, SIEM, workload protection, code security, and vulnerability management - Digital experience tools such as real-user monitoring, session replay, synthetic monitoring, and error tracking - Software delivery, CI visibility, testing, feature flags, and code coverage - Incident response, service catalogs, SLOs, workflow automation, and case management - AI agents, GPU monitoring, AI integrations, and investigation tools The supplied excerpt does not provide enough information to summarize Gartner’s criteria, Datadog’s strengths or weaknesses, or the report’s comparative findings.

Datadog2017-07-113 min readCurated summary

Piecewise regression: When one line simply isn’t enough

Piecewise regression models a timeseries with multiple linear segments when one line is insufficient. Datadog’s approach automatically detects both breakpoints and the number of segments, while avoiding a brute-force search of all possible partitions. It starts with an intentionally overfit model and greedily merges neighboring segments until the increase in error indicates that further merging would lose important structure. ## Objectives - **Automated breakpoint detection** - The algorithm identifies where one linear trend changes into another. - This is necessary for running hundreds of regressions per second without manual input. - **Automated segment-count selection** - The number of segments is not specified in advance. - The method must distinguish between data best represented by one line and data requiring several. - **No continuity requirement** - Adjacent regression lines do not need to meet at their shared breakpoint. - This allows the model to represent discontinuous changes in the data. ## Challenges - **Large search space** - A timeseries can be partitioned in exponentially many ways. - Although dynamic programming is more efficient than brute force, it remains too slow for Datadog’s performance requirements. - A greedy heuristic is used to eliminate large portions of the search space quickly. - **Balancing fit and simplicity** - More segments generally reduce the sum of squared errors. - Using one segment per point could produce nearly zero error but would provide little useful information for interpolation or extrapolation. - The goal is therefore to find the fewest segments that model the data accurately. ## Greedy Merging Algorithm - Begin with approximately **n/2 segments** for a timeseries containing *n* observations. - Fit each segment using ordinary least squares regression. - Repeatedly examine every pair of neighboring segments: - Calculate the increase in total squared error if the pair were merged. - Merge the pair producing the smallest error increase. - Continue merging until only one segment remains. - Record the segmentation state immediately before a merge appears to go too far. - If no merge triggers the stopping rule, select one large segment; otherwise, return the last recorded segmentation. ## Stopping Criteria - A merge becomes a potential stopping point when its increase in total squared error exceeds that of every earlier merge. - To avoid stopping prematurely on data that is fundamentally linear, the increase must also be less than **3% of the total error from a single-line regression**. - The 3% threshold is heuristic but was found to work well in practice. - For data generated from one noisy linear trend, error increases gradually as segments are merged, so no merge qualifies as an adequate stopping point and the algorithm ultimately selects one segment. The method provides a practical compromise between exhaustive optimization and model quality: greedy merging makes automated regression fast, while the error-based stopping rule limits overfitting and preserves meaningful changes in trend.

Datadog2017-07-113 min readCurated summary

Piecewise regression: When one line simply isn’t enough | Datadog

Piecewise regression offers a practical way to model time series whose trends change over time, something a single straight-line regression cannot represent well. The technique divides data into segments and fits a separate regression line to each one, allowing systems such as observability platforms to detect trend shifts more accurately. Its usefulness depends on selecting meaningful breakpoints without overfitting noise. ## Why a Single Regression Line Falls Short - Ordinary linear regression assumes one constant relationship between time and the measured value. - Real-world operational metrics often contain: - Sudden changes in growth rate - Traffic or usage shifts - Deployment-related behavior changes - Periods of increase followed by stabilization or decline - A single line averages these different behaviors, producing inaccurate trend estimates and potentially misleading forecasts. ## How Piecewise Regression Works - The time series is divided into multiple regions by one or more breakpoints. - Each region receives its own regression equation, such as: - Before the breakpoint: one intercept and slope - After the breakpoint: a different intercept and slope - The fitting process searches for the breakpoint that minimizes the combined prediction error across all segments. - Models may require the lines to connect at the breakpoint, preventing unrealistic discontinuities, or allow independent segments when abrupt jumps are meaningful. ## Finding Useful Breakpoints - Candidate breakpoints are evaluated by comparing the residual error produced by different segmentations. - A breakpoint is valuable when it significantly improves the fit rather than merely explaining random fluctuations. - More segments can capture complex behavior, but they also increase the risk of overfitting. - Practical implementations therefore need safeguards such as minimum segment sizes, limits on the number of breakpoints, and validation against noisy data. ## Applications in Observability - Piecewise models can improve the interpretation of infrastructure and application metrics. - They are particularly useful for identifying: - Changes in request volume - Altered resource-consumption patterns - Performance regressions - Long-term growth phases - Recovery or stabilization after an incident - By distinguishing genuine trend changes from normal variation, the method can support better anomaly detection and forecasting. ## Limitations and Tradeoffs - Noisy or sparse data can make breakpoint selection unstable. - A model with too many segments may describe historical noise instead of general behavior. - Sudden outliers can distort regression parameters unless they are handled separately. - Piecewise regression captures trend changes, but it does not automatically explain their causes; engineers still need deployment, traffic, and infrastructure context. Piecewise regression is therefore best treated as a lightweight, interpretable tool for detecting changes in metric behavior. It provides more realistic trend modeling than a single regression line while remaining simpler and easier to operate than highly complex forecasting models.