๐Ÿ”ง DevOps

New Relic

An application performance monitoring platform: a cloud-based observability solution integrating APM, infrastructure, and logs

๐Ÿ“– Detailed Explanation

New Relic, founded in 2008, is a leading company in the field of observability. It started with application performance monitoring (APM) and has since evolved into a full-stack observability platform that provides integrated analysis of metrics, events, logs, and traces (MELT). It is delivered as SaaS, so it can be used immediately without building separate infrastructure, and it offers a free data ingest tier of 100GB per month.

New Relic's core features fall into five main categories. APM provides code-level performance analysis and distributed tracing, while Infrastructure handles resource monitoring of hosts, containers, and cloud services. Logs covers log collection and analysis, and Browser and Mobile track real user experience (RUM). All of this data can be analyzed together with New Relic Query Language (NRQL), which makes it easy to identify correlations.

New Relic's strengths are auto-instrumentation and AI-based anomaly detection. Once you install an agent for major languages such as Java, Python, and Node.js, it automatically tracks transactions, DB queries, and external service calls without code changes. Applied Intelligence uses machine learning to detect abnormal patterns and groups related alerts to reduce alert fatigue. In addition, Service Map visualizes dependencies between microservices.

The pricing model is consumption-based, with charges depending on the amount of data ingested. Costs vary with the data retention period and user type (Full platform user vs Basic user), so it is important to estimate costs in advance. It is also highly compatible with OpenTelemetry, the open-source telemetry standard, so you can collect instrumentation data without vendor lock-in.

๐Ÿ’ป Code Example

Python Application APM Setup

# requirements.txt์— ์ถ”๊ฐ€
# newrelic

# newrelic.ini ์„ค์ • ํŒŒ์ผ ์ƒ์„ฑ
# newrelic-admin generate-config YOUR_LICENSE_KEY newrelic.ini

# newrelic.ini ์ฃผ์š” ์„ค์ •
"""
[newrelic]
license_key = YOUR_LICENSE_KEY
app_name = My Python Application
monitor_mode = true
log_level = info
ssl = true
high_security = false
transaction_tracer.enabled = true
transaction_tracer.transaction_threshold = apdex_f
transaction_tracer.record_sql = obfuscated
transaction_tracer.stack_trace_threshold = 0.5
error_collector.enabled = true
browser_monitoring.auto_instrument = true
"""

# Flask ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์˜ˆ์ œ
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')

from flask import Flask, jsonify
import time

app = Flask(__name__)

@app.route('/api/users/')
def get_user(user_id):
    # ์ž๋™์œผ๋กœ ํŠธ๋žœ์žญ์…˜ ์ถ”์ ๋จ
    # Custom attribute ์ถ”๊ฐ€
    newrelic.agent.add_custom_attribute('user_id', user_id)

    # DB ์กฐํšŒ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ (์ž๋™์œผ๋กœ DB ์ฟผ๋ฆฌ ์ถ”์ ๋จ)
    user = fetch_user_from_db(user_id)
    return jsonify(user)

@app.route('/api/process')
def process_data():
    # Custom transaction ์ด๋ฆ„ ์ง€์ •
    newrelic.agent.set_transaction_name('process_heavy_computation')

    # Custom segment๋กœ ์„ธ๋ถ€ ์ธก์ •
    with newrelic.agent.FunctionTrace('heavy_computation'):
        result = heavy_computation()

    return jsonify({'result': result})

# ๋ฐฑ๊ทธ๋ผ์šด๋“œ ํƒœ์Šคํฌ ์ถ”์ 
@newrelic.agent.background_task()
def process_background_job(job_id):
    newrelic.agent.add_custom_attribute('job_id', job_id)
    # ์ž‘์—… ์ˆ˜ํ–‰
    pass

# ์—๋Ÿฌ ์ˆ˜๋™ ๊ธฐ๋ก
def risky_operation():
    try:
        # ์œ„ํ—˜ํ•œ ์ž‘์—…
        pass
    except Exception as e:
        # New Relic์— ์—๋Ÿฌ ๊ธฐ๋ก
        newrelic.agent.notice_error()
        raise

if __name__ == '__main__':
    app.run(debug=True)

Sending Custom Metrics and Events

import newrelic.agent
from newrelic.api.application import application_instance
import requests
import time

class NewRelicMetrics:
    def __init__(self, insert_key: str, account_id: str):
        self.insert_key = insert_key
        self.account_id = account_id
        self.metric_api_url = "https://metric-api.newrelic.com/metric/v1"
        self.event_api_url = f"https://insights-collector.newrelic.com/v1/accounts/{account_id}/events"

    def record_custom_metric(self, name: str, value: float):
        """์—์ด์ „ํŠธ๋ฅผ ํ†ตํ•œ ์ปค์Šคํ…€ ๋ฉ”ํŠธ๋ฆญ ๊ธฐ๋ก"""
        app = application_instance()
        if app:
            newrelic.agent.record_custom_metric(f'Custom/{name}', value, app)

    def send_metric_api(self, metrics: list):
        """Metric API๋ฅผ ํ†ตํ•œ ์ง์ ‘ ์ „์†ก"""
        payload = [{
            "metrics": metrics
        }]

        headers = {
            "Content-Type": "application/json",
            "Api-Key": self.insert_key
        }

        response = requests.post(self.metric_api_url, json=payload, headers=headers)
        return response.status_code == 202

    def send_custom_event(self, event_type: str, attributes: dict):
        """์ปค์Šคํ…€ ์ด๋ฒคํŠธ ์ „์†ก"""
        event = {
            "eventType": event_type,
            "timestamp": int(time.time()),
            **attributes
        }

        headers = {
            "Content-Type": "application/json",
            "X-Insert-Key": self.insert_key
        }

        response = requests.post(self.event_api_url, json=[event], headers=headers)
        return response.status_code == 200


# ์‚ฌ์šฉ ์˜ˆ์‹œ
metrics = NewRelicMetrics(
    insert_key="NRII-xxxxxxxxxxxx",
    account_id="1234567"
)

# ์—์ด์ „ํŠธ ๋ฉ”ํŠธ๋ฆญ ๊ธฐ๋ก
metrics.record_custom_metric('OrderProcessingTime', 1.5)

# API๋กœ gauge ๋ฉ”ํŠธ๋ฆญ ์ „์†ก
metrics.send_metric_api([
    {
        "name": "custom.queue.depth",
        "type": "gauge",
        "value": 42,
        "timestamp": int(time.time()),
        "attributes": {
            "queue.name": "orders",
            "environment": "production"
        }
    }
])

# ์ปค์Šคํ…€ ๋น„์ฆˆ๋‹ˆ์Šค ์ด๋ฒคํŠธ ์ „์†ก
metrics.send_custom_event("OrderPlaced", {
    "orderId": "ORD-12345",
    "userId": "USR-67890",
    "totalAmount": 99.99,
    "itemCount": 3,
    "paymentMethod": "credit_card"
})

NRQL Query Example

-- ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‘๋‹ต ์‹œ๊ฐ„ ์ถ”์ด
SELECT average(duration)
FROM Transaction
WHERE appName = 'My Python Application'
SINCE 1 hour ago
TIMESERIES 5 minutes

-- ๋А๋ฆฐ ํŠธ๋žœ์žญ์…˜ Top 10
SELECT name, average(duration), count(*)
FROM Transaction
WHERE appName = 'My Python Application'
SINCE 1 day ago
FACET name
ORDER BY average(duration) DESC
LIMIT 10

-- ์—๋Ÿฌ์œจ ์ถ”์ด
SELECT percentage(count(*), WHERE error IS true) as 'Error Rate'
FROM Transaction
WHERE appName = 'My Python Application'
SINCE 24 hours ago
TIMESERIES 1 hour

-- DB ์ฟผ๋ฆฌ ์„ฑ๋Šฅ ๋ถ„์„
SELECT average(databaseDuration), count(*)
FROM Transaction
WHERE appName = 'My Python Application'
AND databaseCallCount > 0
FACET databaseCallCount
SINCE 1 hour ago

-- ์ปค์Šคํ…€ ์ด๋ฒคํŠธ ๋ถ„์„ (๋น„์ฆˆ๋‹ˆ์Šค ๋ฉ”ํŠธ๋ฆญ)
SELECT sum(totalAmount) as 'Total Revenue',
       count(*) as 'Order Count',
       average(totalAmount) as 'Average Order Value'
FROM OrderPlaced
SINCE 7 days ago
TIMESERIES 1 day

-- ์ธํ”„๋ผ: ๋†’์€ CPU ์‚ฌ์šฉ๋ฅ  ํ˜ธ์ŠคํŠธ
SELECT average(cpuPercent)
FROM SystemSample
WHERE cpuPercent > 80
FACET hostname
SINCE 1 hour ago

-- ์„œ๋น„์Šค ๊ฐ„ ์˜์กด์„ฑ ๋ถ„์„
SELECT count(*)
FROM Span
WHERE appName = 'My Python Application'
FACET externalHost
SINCE 1 hour ago

-- Apdex ์ ์ˆ˜ ๊ณ„์‚ฐ
SELECT apdex(duration, t: 0.5)
FROM Transaction
WHERE appName = 'My Python Application'
SINCE 1 day ago
TIMESERIES 1 hour

Setting Up New Relic Alerts with Terraform

# providers.tf
terraform {
  required_providers {
    newrelic = {
      source  = "newrelic/newrelic"
      version = "~> 3.0"
    }
  }
}

provider "newrelic" {
  account_id = var.newrelic_account_id
  api_key    = var.newrelic_api_key
  region     = "US"
}

# variables.tf
variable "newrelic_account_id" {
  type        = string
  description = "New Relic Account ID"
}

variable "newrelic_api_key" {
  type        = string
  sensitive   = true
  description = "New Relic API Key"
}

variable "app_name" {
  type    = string
  default = "My Python Application"
}

# alert_policy.tf
resource "newrelic_alert_policy" "app_policy" {
  name                = "${var.app_name} Alert Policy"
  incident_preference = "PER_CONDITION_AND_TARGET"
}

# ์‘๋‹ต ์‹œ๊ฐ„ ์•Œ๋ฆผ
resource "newrelic_nrql_alert_condition" "high_response_time" {
  policy_id = newrelic_alert_policy.app_policy.id
  name      = "High Response Time"
  type      = "static"

  nrql {
    query = "SELECT average(duration) FROM Transaction WHERE appName = '${var.app_name}'"
  }

  critical {
    operator              = "above"
    threshold             = 2.0
    threshold_duration    = 300
    threshold_occurrences = "all"
  }

  warning {
    operator              = "above"
    threshold             = 1.0
    threshold_duration    = 300
    threshold_occurrences = "all"
  }
}

# ์—๋Ÿฌ์œจ ์•Œ๋ฆผ
resource "newrelic_nrql_alert_condition" "error_rate" {
  policy_id = newrelic_alert_policy.app_policy.id
  name      = "High Error Rate"
  type      = "static"

  nrql {
    query = "SELECT percentage(count(*), WHERE error IS true) FROM Transaction WHERE appName = '${var.app_name}'"
  }

  critical {
    operator              = "above"
    threshold             = 5.0
    threshold_duration    = 300
    threshold_occurrences = "at_least_once"
  }
}

# Slack ์•Œ๋ฆผ ์ฑ„๋„
resource "newrelic_notification_destination" "slack" {
  name = "Slack Alerts"
  type = "SLACK"

  property {
    key   = "url"
    value = var.slack_webhook_url
  }
}

resource "newrelic_notification_channel" "slack_channel" {
  name           = "slack-alerts"
  type           = "SLACK"
  destination_id = newrelic_notification_destination.slack.id
  product        = "IINT"

  property {
    key   = "channelId"
    value = var.slack_channel_id
  }
}

# ์•Œ๋ฆผ ์›Œํฌํ”Œ๋กœ์šฐ
resource "newrelic_workflow" "alert_workflow" {
  name                  = "${var.app_name} Alert Workflow"
  muting_rules_handling = "NOTIFY_ALL_ISSUES"

  issues_filter {
    name = "policy-filter"
    type = "FILTER"

    predicate {
      attribute = "labels.policyIds"
      operator  = "EXACTLY_MATCHES"
      values    = [newrelic_alert_policy.app_policy.id]
    }
  }

  destination {
    channel_id = newrelic_notification_channel.slack_channel.id
  }
}

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "Looking at New Relic APM, the average response time for this endpoint is over 2 seconds. I'll open the trace and check where the bottleneck is."
  • "I pulled the error rate trend versus last week with NRQL, and it has increased since Thursday's deployment. Shall we look at the related error logs together?"
  • "Applied Intelligence detected an anomaly and sent an alert. It says it's a DB connection pool exhaustion pattern."
  • "This month's New Relic cost is higher than expected. It looks like we need to reduce log ingestion or adjust the sampling rate."
  • "Among the APM tools you have experience with, in what situations did you use New Relic, and what problems did you solve?"
  • "How does New Relic's distributed tracing help with debugging microservices? Please explain with a real example."
  • "Have you analyzed performance issues using NRQL? Which queries did you mainly use?"
  • "Do you have experience optimizing the cost of observability tools? How did you manage New Relic usage?"

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "This function's performance is important, so it would be good to wrap it in a New Relic custom segment and measure it individually."
  • "Please don't ignore the error in this catch block; add newrelic.agent.notice_error()."
  • "Adding business context such as user_id as a custom attribute is useful for debugging."
  • "Sensitive information is being included in the logs, so it needs to be masked before New Relic ingests it."

โš ๏ธ Cautions

  • Data cost management: New Relic charges based on the amount of data ingested, so you need to watch out for unexpected cost spikes. In particular, monitor the volume of log ingestion, distributed tracing, and custom events, and adjust the sampling rate when necessary. Filtering out unnecessary data before ingestion with Drop Filters is also a good approach.
  • Preventing sensitive data exposure: When collecting APM and logs, passwords, credit card numbers, personal information, and the like may be sent by mistake. Exclude sensitive parameters with the attributes.exclude setting in newrelic.ini, and apply masking in log parsing rules. Particular caution is needed in environments that require compliance with regulations such as GDPR and HIPAA.
  • Consider agent overhead: The APM agent introduces runtime overhead. In most cases it is under 1-3%, but the overhead increases if the transaction tracer threshold is low or if all SQL is recorded. In production environments, strike a balance with appropriate sampling and threshold settings.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More