Haskell World logo Haskell WorldWrite code, build worlds
Developer Tools

Haskell Profiling to Find Slow Code and Memory Leaks

Your Haskell service handled 200 requests a second last month and now it struggles with 60, and nobody can say which change did it.

A laptop on a wooden desk showing a terminal with a memory usage graph climbing steadily beside lines of code

Your Haskell service handled 200 requests a second last month and now it struggles with 60, and nobody can say which change did it. Guessing at strictness annotations rarely fixes that kind of slowdown, but Haskell profiling usually points at the real culprit within an hour.

This guide covers the workflow I use on production code. The examples assume GHC 9.6 or newer and a cabal project.

What Haskell profiling actually measures

GHC profiling works through cost centres. A cost centre is a label attached to an expression, and the runtime counts how much time and how many bytes get charged to each label while your program runs. When the program exits, you get a report that ranks those labels.

That design has a consequence people miss. The profiler only knows about the cost centres you asked for. If you profile with no annotations at all, everything gets lumped under a handful of top level entries and the report tells you almost nothing. If you annotate every single binding, the annotations themselves change how GHC optimises the code, and the numbers drift away from what your real build does.

Building your project with profiling enabled

Profiling needs every library in your dependency tree compiled in profiling mode, not just your own package. The first build is slow for that reason. On a mid sized service with around 120 dependencies, expect 15 to 25 minutes the first time and normal speed afterwards, because cabal caches the profiled libraries in the store.

The cleanest way to set it up is a separate project file so your normal builds stay untouched. Create a file called cabal.project.profiling next to your main cabal.project and put three settings in it:

  • profiling: True turns on profiled builds for every package.
  • profiling-detail: toplevel-functions adds a cost centre to each top level function, which is the right starting granularity.
  • optimization: 2 keeps the build close to what you ship, if your release build uses that level.

Point cabal at that file when you build, and keep the profiled build directory separate so switching back and forth does not trigger full rebuilds.

Reading the time and allocation report

Run the profiled binary with the RTS option for a time profile, written as +RTS -p -RTS after your normal arguments. When the program exits, a file named after your executable with a .prof extension appears in the working directory.

The file shows totals, a flat list of the most expensive cost centres, then the full call tree. Read them in this order:

  1. Look at the flat list first. Anything above 10 percent of time or allocation deserves attention.
  2. Find that cost centre in the call tree and check the "entries" column. A function that costs 30 percent because it runs 4 million times needs a different fix from one that runs once and takes forever.
  3. Compare individual cost with inherited cost. A high inherited number with a low individual number means the work happens in something it calls.

Pay as much attention to allocation as to time. In Haskell, a function that allocates 40 GB over a run is usually slow because the garbage collector is doing the heavy lifting, not the function itself. Running with +RTS -s shows how much time went to GC. If it is above 20 percent of total runtime, chase allocation before you chase anything else.

A quick example from a real service

On a JSON ingestion service I worked on, the time profile put 41 percent of runtime in a small helper that normalised field names. The entries column showed 9 million calls for 300,000 records, so the helper was running 30 times per record. The fix was not making the helper faster. It was caching the normalised names per schema, which cut total runtime by more than a third.

Heap profiling for memory leaks

Time profiles tell you where work happens. Heap profiles tell you what is sitting in memory, which is how you find space leaks. Since GHC 9.2 you can get a basic heap profile even without a profiled build, using the -hT option, which breaks memory down by closure type. It is a good first check because it costs nothing to set up.

For more detail, use a profiled build and pick a breakdown that fits your question:

OptionBreaks memory down byUse it when
-hcCost centre that produced the dataYou want to know which function is holding memory
-hyType of the dataYou suspect a particular structure, like a growing Map
-hdClosure descriptionYou see thunks piling up and need to know which ones
-hTClosure type, no profiled build neededQuick first look on a normal build

Turn the .hp output into a graph with hp2ps or eventlog2html. A healthy service shows a flat band. A leak shows a band that climbs steadily and never comes back down, and the label on that band is your suspect.

The classic leak pattern is a lazy accumulator: a counter or Map updated in a loop with lazy functions, building a chain of thunks that only gets evaluated at the end. Switching to strict variants like foldl' or Data.Map.Strict fixes most of them. Our article on foldr vs foldl and when to use each one explains why the strict fold matters for exactly this case.

Why "annotate everything" is bad profiling advice

A lot of older tutorials tell you to compile with -fprof-auto and annotate every binding. I think that is the wrong default for real projects, and the reason is optimisation.

Cost centres act as barriers. GHC cannot inline a function across a cost centre boundary in the same way, and it cannot fuse list pipelines that cross one. Annotate every binding and you can turn a fused, allocation free loop into one that allocates heavily, then the profiler faithfully reports that new allocation as your bottleneck. You end up optimising a problem that only exists in the profiled build.

Start with toplevel-functions or even exported-functions. When a hot spot shows up, add manual SCC pragmas inside that one function to split it further. You get detail exactly where you need it and the rest of the program stays close to its real shape.

Also sanity check your conclusions against a normal build. If the profile says a change should save 30 percent, time the unprofiled binary before and after. If the real saving is 3 percent, the profile misled you.

A repeatable profiling routine

Profiling works best as a habit, not an emergency tool. The routine I recommend for teams looks like this:

  • Keep a small benchmark input checked into the repo that takes 10 to 30 seconds to process. Short enough to run often, long enough for stable numbers.
  • Profile on that input before every release that touches a hot path, and save the .prof file alongside the release notes.
  • Diff the top 15 cost centres against the previous release. Regressions show up as new names or big jumps in entries.

GHCi pairs well with the profiler for testing small strictness fixes before a full rebuild, as described in using GHCi as your daily Haskell workflow.

Frequently asked questions

Does profiling slow down a Haskell program?

Yes. A profiled build typically runs 20 to 100 percent slower than a normal build, depending on how many cost centres you add. The relative ranking of hot spots is usually still accurate, which is what matters. Always confirm a fix by timing the normal build afterwards.

How do I find a space leak in Haskell?

Start with a heap profile using -hT on a normal build and look for a band that grows without dropping. Then switch to a profiled build with -hc or -hd to see which function or closure owns that memory. Most leaks turn out to be lazy accumulators or caches that never evict entries.

Why does cabal rebuild everything when I turn on profiling?

Every dependency needs its own profiled build, which cabal stores separately, so the cost is paid once per dependency version. Keeping profiling settings in a separate project file stops your normal builds from being affected.

SR
Sonja Reiter

Sonja Reiter contributed to three major open source projects and started writing documentation when she noticed most tooling guides were written by people who had never taught anyone to use them. She covers build tools, package ecosystems, and the invisible quality-of-life differences between development setups.

More posts by Sonja

More in Developer Tools

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto