Python Developer interview question

How do you profile a slow Python service?

Profile a slow Python service under representative load: separate external latency from CPU and allocation cost, use tracing plus cProfile or py-spy, optimise the measured hot path, then compare against the baseline.

Direct answer

What a strong answer covers

How it works

Start by classifying the slowness with traces and metrics: time spent waiting on the database or other services is not a Python problem and no profiler will fix it. For CPU time, py-spy attaches to the running process without code changes and produces flame graphs under real traffic; cProfile gives call counts in a reproducible script; tracemalloc or memray reveal allocation hot spots. Fix the single largest contributor, re-measure with the same workload, and keep the before and after numbers.

Example

An endpoint with 800 ms p95 turned out to spend 600 ms serialising a large ORM result with a generic to_dict; py-spy showed the frames, a hand-written serialiser for that endpoint brought it to 150 ms, and a load test with the same request mix confirmed the gain. The database queries themselves were already under 40 ms.

Common mistakes

  • Profiling a single request on a laptop and extrapolating to production traffic.
  • Micro-optimising loops while an N+1 query dominates the trace.
  • Applying caching or Cython before confirming which frames are actually hot.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
Python Developer interview questions