Courseiva
PCDOEChapter 11 of 17Objective 2.3

Distributed Tracing and Profiling with Cloud Trace and Cloud Profiler

Distributed tracing and profiling are two tools that help you find out exactly why your cloud application is slow or failing. For the PCDOE exam, you need to understand how Google Cloud Trace tracks the path of a single user request across multiple services, and how Cloud Profiler measures the performance of your code itself — then use that information to fix real-world application bottlenecks.

12 min read
Advanced
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Distributed Tracing and Profiling with Cloud Trace and Cloud Profiler

The Restaurant Kitchen Log Analogy

A busy restaurant kitchen on a Saturday night. The head chef is trying to figure out why a specific table's order is taking so long.

She has a small whiteboard where she tracks each order as it comes in. When the waiter calls out 'Table 22: two steaks, one well-done', she writes it down. As the order moves from the grill station to the vegetable station to the plating station, a junior chef writes down the time it leaves each station and which cook handled it. When table 22 finally gets their food, the head chef looks at the whiteboard. She sees that the well-done steak sat on the grill for eight minutes because the grill cook was juggling five other orders. The vegetables were done in two minutes but waited four minutes on the counter because the plating chef was waiting for the steak. This whiteboard log is her 'distributed trace' — it shows the whole journey of that one order through every station in the kitchen.

Now imagine she also wants to know which cook is wasting time between tasks. She uses a stopwatch to time each cook during a busy rush. She finds that the vegetable chef spends three minutes between every order washing her knife, even though she only needs thirty seconds. That stopwatch data is her 'profiler' — it shows where the team is wasting performance time, not just where individual orders are slow.

How It Actually Works

Let us start with a simple idea. When you use a website or a mobile app, you send a request — click a button, load a page, place an order. That single request might travel through many different computer programs or 'services' before it gives you an answer. For example, a request to an online shop might first hit a web server that checks your login, then a database that looks up the product price, then a payment service that processes your credit card, and finally a notification service that emails you a receipt. Each of these services is a separate piece of software, often running on a different computer or even in a different data centre.

If the whole request takes five seconds, which service caused the delay? Is the web server slow? Is the database congested? Is the payment service waiting on an external bank? This is the problem that 'distributed tracing' solves. A distributed trace attaches a unique ID to every incoming request — think of it like a tracking number on a parcel. Every time the request enters or leaves a service, that service records a timestamp and a label called a 'span'. A span is a single unit of work, like 'checking user permissions' or 'querying the product database'. All these spans, linked by the same trace ID, are then collected and sent to a central tool — Google Cloud Trace.

Cloud Trace then assembles all the spans in order. It shows you a timeline: the request hit the web server at time 0, the database query ran from 0.2 seconds to 2.1 seconds, the payment call ran from 2.3 seconds to 4.8 seconds. You can instantly see which span took the longest. That long span is your 'performance bottleneck' — the place where you should spend your time optimising. Cloud Trace also aggregates data across many requests, so you can see the average latency of every service over time.

Now, what if a service is not slow because it is waiting on something external, but because the code inside it is inefficient? For example, a function that sorts a list of a million items using a slow algorithm. Distributed tracing would show that the service takes one second to respond, but it would not tell you that the sorting function itself is the cause. This is where 'profiling' comes in. A profiler is a tool that watches your computer code while it runs and measures how much time is spent in each function. It samples the program's execution thread — like taking a snapshot every millisecond — and records what line of code is being executed at that moment. Over thousands of snapshots, it builds a picture: '50% of this service's CPU time is spent in the sort() function'.

Google Cloud Profiler is Google's managed profiling service. It runs continuously on your production servers with very low overhead, meaning it does not slow down your application. It shows you a 'flame graph' — a visual chart where each rectangle represents a function, and the width of the rectangle shows how much CPU time that function consumed. You can compare profiles from different versions of your code to see if a recent change introduced a new bottleneck.

In summary, Cloud Trace tells you where time is spent across multiple services in a single request, while Cloud Profiler tells you where time is spent inside the code of a single service. Together, they give you the full picture of why your application is slow and exactly what you need to improve.

A user request flows through six services; each sends span data to Cloud Trace, while the Cloud Profiler agent on one bottleneck service produces a flame graph.

Walk-Through

1

Instrument the Application

Add the Cloud Trace client library or use auto-instrumentation via Anthos Service Mesh. This enables your application to generate trace spans. Without this step, no trace data exists to analyse.

2

Propagate the Trace Context

When a service calls another service, it must forward the trace ID and span ID via HTTP headers. If propagation is missing, the trace breaks into disconnected fragments, making it impossible to see the full request path.

3

Collect and View Traces in Cloud Trace

Spans are sent to Google Cloud Trace either synchronously or asynchronously. In the Cloud Console, you can view a list of traces, filter by attributes (e.g., latency, service name), and click into a trace to see the waterfall diagram of spans.

4

Analyse the Waterfall Diagram

Identify the span with the highest latency — that is likely your bottleneck. Check if the span is waiting on a downstream service or is consuming CPU internally. This step tells you which service needs attention.

5

Deploy and Run the Cloud Profiler Agent

Install the Cloud Profiler agent on the service identified as the bottleneck. The agent samples the running code at regular intervals and sends profiling data to Cloud Profiler in the Google Cloud Console.

6

Interpret the Flame Graph in Cloud Profiler

Open the Cloud Profiler page and view the flame graph. Each box represents a function; wider boxes indicate more resource consumption. Identify the widest box to locate the specific function or line of code causing the slowdown.

What This Looks Like on the Job

An IT professional responsible for a Google Cloud-hosted application would use Cloud Trace and Cloud Profiler in a systematic way to diagnose and fix performance issues. Here is a concrete scenario:

A company runs an e-commerce platform on Google Kubernetes Engine (GKE). Users start complaining that the checkout page takes over ten seconds. The site owner asks the DevOps engineer to investigate.

Step 1: The engineer opens the Google Cloud Console and navigates to Cloud Trace. She looks at the 'Trace list' to see recent requests to the checkout service. She filters by 'latency > 5 seconds' to isolate the slowest requests. She clicks on one trace to see its waterfall diagram.

Step 2: The waterfall diagram shows four spans. The first span is 'checkout-service: authenticate user', which took 200ms. The second span is 'checkout-service: calculate shipping', which took 100ms. The third span is 'checkout-service: process payment', which took 8,000ms. The fourth span is 'checkout-service: send confirmation email', which took 300ms. The engineer immediately sees that the payment processing span is the bottleneck — it accounts for 80% of the total latency.

Step 3: The engineer now wants to understand why the payment processing function is so slow. She opens Cloud Profiler and selects the checkout service. She looks at the 'CPU time' flame graph for the last hour. The flame graph shows that 70% of the CPU time is spent inside a function called 'validateCreditCardNumber()', and within that function, 60% of time is spent on a string parsing routine.

Step 4: Based on the profiler data, the engineer inspects the code for validateCreditCardNumber(). She discovers that the function is using a regular expression that is extremely inefficient for long card numbers. She rewrites the function to use a simpler character-by-character check. She deploys the fix to a staging environment and uses Cloud Trace to compare latency before and after the code change. The payment span drops from 8,000ms to 200ms.

Step 5: The engineer monitors Cloud Trace's latency report for the next week to confirm the improvement holds. She also sets up a Cloud Trace-based alert: if the payment span latency exceeds 1,000ms for more than five minutes, the on-call team gets paged.

In this real-world workflow, the engineer uses Cloud Trace to locate which service is slow, then Cloud Profiler to find the specific line of code causing the slowdown, and finally Cloud Trace again to verify the fix worked. This end-to-end process is exactly what the PCDOE expects you to understand.

How PCDOE Actually Tests This

The PCDOE exam tests your understanding of Cloud Trace and Cloud Profiler in specific, predictable ways. Here is exactly what you need to know.

First, the exam frequently asks about the difference between 'trace' and 'span'. A trace is the complete path of one request across all services. A span is one unit of work within a trace — one hop from service to service or one function call within a service. The exam will give you a description and ask you to identify which is which.

Second, the exam tests the 'span context propagation' mechanism. When a request moves from service A to service B, the trace ID and span ID must be passed along via HTTP headers (specifically, the 'x-cloud-trace-context' header in Google Cloud). The exam may present a scenario where tracing stops working between two services and ask you what the likely cause is — almost always that the context header was not forwarded.

Third, the exam tests the concept of 'sampling'. Cloud Trace does not collect every single request — that would be too expensive and noisy. Instead, it uses a sampling rate (e.g., 1 in 100 requests). You may be asked to advise a customer on how to increase or decrease the sampling rate, or to understand that changing the rate affects the accuracy of latency statistics.

Fourth, the exam tests Cloud Profiler's 'agent' and 'agentless' modes. You need to know that Cloud Profiler supports both an agent that runs inside your application (for Java, Go, Node.js, Python, and Ruby) and an agentless mode for some languages. The exam may ask you to choose the correct agent type for a given language.

Fifth, the exam tests the types of profiles Cloud Profiler collects. There are four main types:

CPU time: how much CPU each function consumes

Heap: how much memory each function allocates

Wall time: the real wall-clock time each function takes (including time waiting for I/O)

Allocation: how many objects each function allocates

You may be asked to select the correct profile type for a given scenario.

Sixth, watch for traps around 'always-on profiling'. Cloud Profiler is designed to run continuously in production with very low overhead (typically less than 1% CPU). The exam expects you to know that it is not a one-shot diagnostic tool — it is a continuous monitoring tool.

Seventh, the exam loves testing 'service mesh tracing'. You may be asked how Cloud Trace works with Google Cloud's service mesh (Anthos Service Mesh). The key fact: the sidecar proxies automatically generate trace spans for every request, so you do not need to manually instrument your code.

Finally, be ready for questions that ask you to choose between Cloud Trace and Cloud Profiler for a specific use case. The rule of thumb is: if the problem is about latency between services, use Cloud Trace. If the problem is about high CPU or memory usage inside a service, use Cloud Profiler.

Key Takeaways

Cloud Trace tracks the end-to-end journey of a single user request across all microservices using a unique trace ID and spans.

Cloud Profiler continuously samples your code's resource usage (CPU and memory) with less than 1% overhead, identifying the exact functions that consume the most resources.

Span context is propagated between services via the 'x-cloud-trace-context' HTTP header; broken propagation is the most common cause of missing traces.

Cloud Trace uses a configurable sampling rate — increasing it improves statistical accuracy but incurs higher cost and data volume.

Cloud Profiler offers four profile types: CPU time, heap, wall time, and allocation — each answers a different performance question.

When a service mesh like Anthos Service Mesh is used, sidecar proxies automatically generate trace spans without any code instrumentation.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Cloud Trace

Tracks latency across multiple services for a single request

Uses spans and trace IDs to build a waterfall diagram

Answers: 'which service in the request path is slow?'

Cloud Profiler

Measures CPU, memory, and wall time inside a single service's code

Uses sampling to build a flame graph of function-level resource use

Answers: 'which function inside a service is consuming the most resources?'

Synchronous Tracing (Cloud Trace)

Each span is sent to Cloud Trace as soon as it completes

Real-time visibility, but can impact application throughput during bursts

Requires network connectivity to Cloud Trace API at time of request

Asynchronous Logging

Logs are written to a local file or buffer first, then sent in batches

Lower overhead at request time, but introduces delay in data visibility

Tolerates temporary network outages without data loss

Anthos Service Mesh Auto-Instrumentation

Sidecar proxy automatically generates spans without code changes

Works with any HTTP-based service in the mesh

Traces are generated at network proxy level, not application function level

Manual Client Library Instrumentation

Requires adding code to each service using a language-specific library

Provides more detailed, function-level spans within the service

Gives the developer full control over which operations become spans

Watch Out for These

Mistake

Cloud Trace and Cloud Profiler do the same thing — they both measure performance.

Correct

Cloud Trace measures request latency across multiple services, while Cloud Profiler measures resource consumption (CPU, memory) inside a single service's code.

Both tools live in the 'observability' category, so beginners lump them together. But they answer completely different questions: 'where is the delay?' versus 'what is eating the CPU?'.

Mistake

You must manually add tracing code to every service to use Cloud Trace.

Correct

Cloud Trace works with several auto-instrumentation mechanisms, including the Google Cloud client libraries and Anthos Service Mesh sidecar proxies, which generate traces without code changes.

Many beginners come from manual logging mentalities and assume the same applies to tracing. Google Cloud’s auto-instrumentation is one of its key selling points against open-source alternatives.

Mistake

A slow trace always means the slowest span is the root cause of the problem.

Correct

A slow span is a symptom, not necessarily the root cause. The slow span might be waiting on a downstream service, a locked database, or a resource constraint. You must drill deeper with Cloud Profiler or other logs.

It is tempting to assume causation from correlation. The exam tests that you know correlation does not equal causation — a slow span could be the victim, not the perpetrator.

Mistake

Cloud Profiler can only profile code running on Google Compute Engine.

Correct

Cloud Profiler supports applications running on Google Compute Engine, Google Kubernetes Engine, App Engine, and even on-premises or other clouds, as long as the agent can reach the Google Cloud API.

Beginners often think Google Cloud tools are locked to Google Cloud infrastructure. In reality, the profiler agent can be installed on any Linux server with internet access.

Mistake

If you increase the Cloud Trace sampling rate to 100%, you get better data with no downsides.

Correct

Increasing the sampling rate increases the volume of trace data collected, which raises storage costs and can cause network overhead. Most teams use a 1-10% sampling rate for production.

The 'more is better' fallacy. Beginners do not recognise the cost-performance trade-off. The exam will test whether you know that 100% sampling is neither practical nor cost-effective.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

Is Cloud Trace free to use?

Cloud Trace has a free tier of 250,000 spans ingested per month. Beyond that, you are billed per span. Profiler has no cost for the agent itself, but you pay for the storage of profiling data in Google Cloud's operation suite.

Can I use Cloud Trace with applications not running on Google Cloud?

Yes, you can. You can send trace data from any application that can make HTTPS requests to the Cloud Trace API, as long as you have a Google Cloud project and appropriate authentication.

What is the difference between Cloud Trace and Cloud Monitoring?

Cloud Trace is specifically for understanding request-level latency with spans and traces. Cloud Monitoring (formerly Stackdriver Monitoring) collects metrics, uptime checks, and dashboards for overall system health. They are complementary.

Does Cloud Profiler work with multi-threaded applications?

Yes, it supports multi-threaded and multi-process applications. The agent profiles all threads in a process and aggregates the data into a single flame graph.

How do I increase the Cloud Trace sampling rate?

You configure the sampling rate in your application code by passing a SamplingContext object to the Cloud Trace client library when you create a tracer. For auto-instrumented environments, you set an environment variable like TRACE_SAMPLE_RATE.

What happens if I stop the Cloud Profiler agent on a production server?

Then no new profile data is collected for that server. Existing profile data is retained in Google Cloud for the configured retention period (default 30 days). The agent must be restarted to resume data collection.

Terms Worth Knowing

Keep going

You've finished Distributed Tracing and Profiling with Cloud Trace and Cloud Profiler. Continue through the PCDOE study guide to build a complete picture of the exam.

Done with this chapter?