Sleep Hygiene For Software Engineers
Software engineers know the importance of sleep; posts extolling its virtues (or the problems associated with its absence) regularly reach the front page of HackerNews. In fact, around the time I finished this post there were two articles on the front page: Fitful nightly sleep linked to chronic inflammation, hardened arteries and Why Sleep Deprivation Kills. Yikes! There’s invariably a comment on sleep-related posts saying something to the effect of, “I know getting good sleep is important, but I don’t know why I’m not sleeping well and I don’t know how to resolve it even if I did!”. Academia offers little help as there’s only a handful of studies focusing on sleep solely for the software engineer.
This post is an attempt to shed some light on why software engineers may be predisposed to poorer sleep and, more importantly, to detail specific steps to address this.
The Challenge of Sleep as a Software Engineer
There are five major issues we have as software engineers with respect to sleep: a propensity to problem solve, a lack of obstacles, insufficient social interactions, an irregular light cycle, and sedentariness.
A Propensity to Problem Solve
Software engineering is one of the more cognitively demanding professions. As we code, we attempt to be the machine on which we are working and maintain the software state in our heads: “If this variable is more than this value, this branch will be followed, meaning I need to correct this other variable.”, etc. As we improve as software engineers, we can maintain increasingly larger and more complex states. This process becomes second nature. Thus, it’s often the case that after a long day of embodying the computer we step away and find that, despite our best efforts, that process hasn’t stopped. We still embody the computer! We take on the thousand-yard stare but instead of reliving war traumas, we’re reliving code traumas, continuing to work on the problem we’ve ostensibly removed ourselves from.
Of course, this isn’t universally a Bad Thing. We’ve all experienced the phenomenon of not being able solve a problem, only to go for a walk and think about other things, and to have the solution come to us effortlessly (and yet despite knowing this I still tell myself, “Just five more minutes working on this problem, then I’ll get it!” repeatedly for an hour).
No, the problem arises when we attempt to “wind down”, “go to sleep”, “suspend to RAM” - damnit, I’m embodying the machine now.
We’re so used to being in our heads, so used to self-directed problem solving, so used to maintaining state and control flow, the task of simply doing nothing, of letting go, is Herculean. The metaphor of ruts in one’s brain comes to mind. Our ruts as software engineers are formed between the problem and the solution and bear the weight of problems our wetware was never designed to deal with, traversed so regularly and with such intensity that they might be mistaken, if examined, as the sulci of the brain itself.
Juxtapose this with sleep. Sleep, especially deep sleep, comes after consciously letting go of problems and for software engineers especially, problem solving. I think of it as anti-problem solving. It’s quite literally a suspension of the belief that a given problem, really all problems, need be solved right now. It’s the walk we take when we’ve attempted one too many solutions unsuccessfully only it’s in our brains and without our conscious selves.
A Lack of Obstacles
Not only have we as software engineers trained ourselves to constantly problem solve, there are few if any obstacles preventing us from doing so. Available to us at any moment are innumerable blogs, lectures, and tutorials. We need only take a step in any digital direction to find open source projects with charismatic maintainers beckoning us to join the movement or productivity gurus promising us techniques for working smarter.
Beyond endless resources, the cost of tools is plummeting: I’m writing this on a 2012 ThinkPad (Apple people don’t hurt me) that I bought off of Electronic Bay, running Ubuntu (Arch people don’t hurt me), onto a blog that could be freely hosted on Github (I’ve chosen to make it private because I’m a fragile little flower). Most of these tools are relatively portable too; we don’t need to be in a specific location to paint, our canvas moves.
It’s similarly criminal to consider this a Bad Thing - anyone with a combination of interest and discipline can become a software engineer. Perhaps an entirely novel early cancer detection algorithm is in some child’s brain who, were she not exposed to these resources and tools, would never be able to give this gift to society.
By design, potential solutions to the problems we’re working on are a Google search away. There’s no reason not to keep problem solving as the split-second insight we have can be acted upon whether we’re sitting on a beach in Daytona or laying on a mattress in Denver. We may even discover new problems we want to work on while falling down the rabbit hole. Combine this with Silicon Valley hustle culture and we have a recipe for profound sleep issues. “I’ll sleep when I’m dead.” becomes “I’ll sleep when I get my Series A.”
Sedentariness
The stereotype of software engineers as unhealthy neckbeards living in our parent’s basement is dated. My parent’s basement frequently floods so I can’t stay there despite my insistence that a little water is fine. Regardless, in my experience software engineers are mostly healthy and the discipline that the job requires means they can be some of the most dedicated people to self-improvement (to a fault, recall the aforementioned silicon valley hustle culture). That said, there’s little denying that it’s not ideal to remain stationary as much as we do.
It never ceases to depress me when a post on HackerNews pops up related to the buzzkill that no amount of exercise makes up for significant sitting or that standing is little, if at all, better. While these articles are often related to more holistic measures of health, sleep is surely affected by the lack of movement as exercise (heavy qualifier: when done at the right time) helps facilitate sleep. Perhaps we should all use something like Stephen Wolfram’s treadmill desk but personally I have found it challenging to solve particularly difficult problems while standing, much less while walking a 10k.
Insufficient Social Interactions
Being interrupted while in the middle of a complex problem is frustrating for members of any profession. We like to tell ourselves as software engineers that our relationship with interruption is particularly bad (in fact, we’re not on speaking terms at the moment). I believe this is mostly true: interruptions reset our mental machine’s state, a state that may have taken hours to get to. I’m firmly on team #closedoffice for this reason.
Yet, “we humans are social creatures” to quote everyone ever. With respect to sleep, the problem with a lack of human interactions is less related to some biological deficit and more related to having another reason to exist mostly in our own heads (although a reasonable argument could be made that these are one and the same). As someone who genuinely enjoys coding and has worked in small teams (and on isolated projects) my entire professional career, I can recall a handful of days where I didn’t communicate with anyone at all much less have a substantive conversation.
An Irregular Light Cycle
It’s typical to frame sleep issues for office workers in the context of a lack of sunlight. While this is true for software engineers as well, we also have the issue of fixating on 3840 x 1600 pixels of sun-replicating ultrawide glory!!!!!!!!!!!!!!!! for our entire day and into the night. Thus, we often miss the suppression of melatonin in the morning from natural sunlight and the lack of melatonin suppression from natural darkness in the evening.
Technical solutions exist for this issue. Indeed, thanks largely to the popularity of software like f.lux, most operating systems (including iOS and Android) now support some sort of blue light removal out of the box. As far as I’m aware, there hasn’t been a rigorous study on whether or not these technologies (including blue light glasses) actually help us sleep. I suspect that they likely do to some nonzero extent. For those of us that struggle with sleep, however, I worry that they provide an excuse to continue looking at screens because we think “no blue light, no problem!”. I consider it axiomatic that light that we are consciously aware of, regardless of wavelength, promotes wakefulness. In other words, when it comes to sleep the best pixel is a dead pixel.
Sleep Hygiene for Software Engineers
The following are the steps I’ve taken to address the above issues. They’ve worked for me - I’ve gone from a chronic insomniac (three to four hours of sleep per night, at best) to someone who only occasionally suffers from a poor night of sleep. I suspect they’ll work for you too.
-
Set strict work hours including wind down time
The only strategy that has worked for me here is one of zero-tolerance: I’m only allowed to work from 9am - 5pm without exception. Didn’t finish a problem I was working on that day? Think that a solution could be found after only a couple more minutes of work? Can’t remember if that bit of code was integer or floating point division and THAT’S THE BUG!? Tough shit. Only when I am ruthless with my time in this way do the embodied clock-ticks stop. My brain seems to get the hint that I’m not going to do anything about a given issue no matter what, and moves most of the problem solving to the back burner (or takes it off the proverbial stovetop altogether).
This has been the single most effective technique for improving my sleep but unfortunately one of the most difficult. As I’m no longer working a minute more than my schedule dictates, it’s helpful to plan “wind down time”. During this time (usually about 30 minutes or so), I note the problems I am working on and what I think the potential solutions might be such that I can start again the next day with minimal warm up time. As an aside, I also like to note what I’ve done that day. This helps combat the feeling of insufficient accomplishment that can occur on days where I have to stop working on an unsolved problem.
-
Fight the productivity-above-all mindset
Being a proud member of the software development community can be a double-edged sword. It’s incredibly inspiring to see software engineers blaze digital trail - people like Andrew Kelley building a new programming language (among other things), Jessie Frazelle building new server infrastructure (among other things), or Drew DeVault building a new software forge (among other things). Not only are these people in particular seemingly great engineers, they’re also great writers. I challenge you to find a random blog post of theirs and not have the feeling that it’s time to build.
Unless, of course, you’re trying to sleep. Then, through absolutely no fault of their own, these engineers (and perhaps moreso the engineer that we don’t know with absolute certainty exists but are quite sure is working on a competing product) become unsilenceable muses. If it gets really bad, we may even adopt a sort of “productivity-above-all mindset” where nothing is worthwhile unless it results in some sort of “improvement” either to our creations or to ourselves.
There are two ways I’ve found to fight this. The first is to try to normalize our fellow software engineers. Surely Andrew, Jessie, and Drew have struggled and have made sacrifices to get to where they are today, as we all have. Drew even has a great blog post on the happinesses and stresses of full-time FOSS work. The second (and more effective for me personally) is to turn the productivity mindset back on itself. I regularly have to tell myself that shutting down the mental machine for a bit will make me more productive when it comes back on in almost every conceivable way.
I think we as software engineers don’t take enough lessons from the great physical athletes: LeBron James and Giannis Antetokounmpo (arguably two of the top three NBA players right now for those who don’t follow basketball) are known nappers. LeBron is notorious for being able to recall minute details from plays that happened years ago - I have little doubt this is due to the importance he places on work and rest.
-
Take movement breaks
Like the great athletes, us normies need to move. Adhering to the guidelines for cardiovascular health of 2 hours and 30 minutes of moderate to vigorous exercise a week seems to also help with sleep quality.
My personal experience has been that short but frequent movement breaks throughout the day are an important supplement to (and, in a pinch, can serve as a temporary replacement for) more vigorous exercise. It’s a case of something being better than nothing, even a little something. More frequent little somethings are better still. I try to do a 5 minute break every hour. This can be a brief walk, a couple airsquats, or petting the Shiba. Anything that gets me out of my work position and, at the risk of this post being littered with cliches, “gets the blood flowing”.
Taking breaks to move frequently is almost as challenging as being strict with work hours. While this is in part due to breaks being another interruption, my bigger difficulty with breaks is that I simply lose track of time. I haven’t found a great technical solution to this that gets break reminders right - at the moment I simply set a repeating event in Google Calendar that pops up with a reminder every hour on weekdays. Other options include IDE extensions (like pomodoro timers) or setting a
systemd
timer. If you’ve found a good solution for this, @ me! -
Schedule the day such that you can interact with some people in earnest
I’ve recently heard the quote that, “A problem shared is a problem halved.” and found this to be a perfect description of why we problem-solving software engineers should strive for more personal interactions. It highlights the nuance here that we benefit more than simply as a result of getting out of our heads. One of my favorite phenomenons occurs when attempting to ask a question on Stack Overflow and, by virtue of forming the question, the answer becomes obvious. The same holds true for explaining the problems I’m working on to others, even if they have no software background. Thus, this step has a two-fold benefit with respect to sleep: problems that keep us awake are more easily solved and it makes it easier to stop ruminating on those problems altogether.
-
Get outside
Yes, getting outside gets us away from our screens. But I’m of the opinion that getting outside, returning to our roots, putting our feet in the dirt, and other crap like this have uncountable other benefits for not only sleep but effectively all biological processes. Despite this, scientists have started enumerating them, the ambitious little devils! A few of my favorite effects that have been shown are that every hour outside advanced sleep onset by ~30 minutes, or that a weekend in the wilderness can reset our biological clock.
Beyond the biological, staring at the night sky in particular reinforces the belief that I’m an ant on a blue dot. I’ve found no technique more powerful for putting any issues I have (that might prevent sleep) to rest.
Sleep Hygiene for Er’body
It’s also worth mentioning the typical recommendations for sleep hygiene applicable to everyone and not just the lowly software engineer.
-
Maintain consistent bed / wake times, even on the weekends (to avoid social jetlag).
Wake time is more important than bed time for our circadian rhythm, so we should try to wake within the same 15 minute block every day.
-
Optimize your bedroom for sleep.
There are a couple crucial aspects here:
-
Temperature
I’ve listed temperature first for a reason: I believe temperature plays a bigger role in sleep than most people realize. Recommendations often suggest a temperature of around 64°F (18°C). Growing up beyond the wall in Michigan, I prefer colder - closer to 60°F. Find what works best for you.
Note that memory foam beds tend to hold on to heat more than traditional metal spring beds.
-
Light
Even if we eliminate sources of light we control, other sources of light (e.g. light pollution) can still pose a problem for sleep. I’ve used this eye mask for a number of years. It’s contoured such that the mask itself doesn’t sit on your eyelids which helps if you are a warm sleeper. Blackout curtains like these are a great option if you don’t like wearing an eye mask or if the eye mask doesn’t provide sufficient coverage. Remember, though, that light in the morning helps wakefulness. I’ve found that waking up in what is effectively a cave can cause drowsiness that persists throughout the day.
-
Sound
I’ve used these earplugs for a number of years, mostly because you can get a metric ton of them from Amazon. I’m still working through the second box I ever ordered. I’d recommend evaluating multiple earplug shapes and finding one that fits your ear best. I can’t comment on white-noise as I prefer silence when sleeping. Again, don’t underestimate the power of finding what works specifically for you (and the dark side of the Force).
-
-
Avoid caffeine “later in the day”.
The average half-life of caffeine is about five hours for healthy individuals but can be nearly double in some individuals. I’ve found for myself that caffeine ingested any later than noon will affect my sleep that day. Interestingly, I’ve noticed that sustained daily caffeine intake can have a cumulative effect resulting in consistent waking about two hours (or perhaps one sleep cycle?) after going to sleep. If I remove caffeine completely my sleep maintenance goes back to normal. The latter points may be the placebo effect rearing it’s incredibly effective head. Regardless, I recommend experimenting with caffeine intake and taking regular breaks from consuming it at all (if for no other reason than to reduce dependence).
Another note: decaffeinated beverages still have some caffeine so those with hypersensitivity should be cautious.
-
Avoid alcohol “later in the day”. No nightcaps.
I like having a beer as much as the next brogrammer but imbibing invariably leads to poorer sleep. There’s a number of reasons for this including affecting the specific brainwaves that occur during sleep. Subjectively, the biggest issue I have with alcohol is that it tends to make me feel congested and dehydrated (more on both of these in a bit).
There are a couple recommendations related to Cognitive Behavioral Therapy for Insomnia (CBTI) that you’ll often see as well:
-
Don’t go to bed unless you are sleepy.
-
If you don’t fall asleep after 20 minutes, get out of bed.
-
Use your bed only for sleep and sex.
Having done CBTI with some success in college, I’m going to take the liberty of modifying these to:
-
Don’t go to bed unless you are sleepy.Don’t go to bed unless you are sleepy or if you’re starting to feel anxious about how late you’ve been up (more about sleep anxiety in a bit).I’ve gotten into situations where I’ve been trying to stay out of bed because I don’t feel like I will fall asleep. If I have an engagement (particularly early in the morning), feeling the hours tick by can be a major source of anxiety. This actually makes me less likely to fall asleep than simply just attempting to go to bed even though I’m not that tired.
-
If you don’t fall asleep after 20 minutes, get out of bed.If you have the thought, “Why aren’t I falling asleep?”, get out of bed.Assigning a required time to fall asleep was problematic for me. Not only is 20 minutes short for someone with sleep issues, I found myself continually wondering if enough time had passed that I should get up (and you should definitely not have a clock visible from your bed). Instead, I found it more helpful to get out of bed if I had a thought questioning my sleep or lack thereof. The point here is to reframe your bed as the place you sleep, not to train yourself what 20 minutes feels like.
-
Use your bed only for sleep and sex.Do not look at screens in or around bed.I don’t know if the creators of CBTI envision a Constanzaesque scenario of cooking in bed, but in my experience it’s more effective to just restrict the things that actively interfere with sleep like screens. If cooking in bed puts you right to sleep, I say go for it (and make the most amazing cookbook ever)! Personally, I’ve found reading fiction very sleep inducing - my pet theory is that it creates a conscious dream state that makes transitioning to an unconscious dream state easier.
For those that like reading on an e-reader, I’ve found that a non-backlit Kindle (I have the 6th gen) with a headlamp that has a dimmable red light has been a great setup for me (and my partner) - the relaxation of fiction seems to outweigh the arousal from a small amount of light.
Anecdotal Sleep Hygiene
-
Hydrate
I’ve found that my sleep quality is highly correlated with my hydration. There appears to be some conflict in the literature as to whether or not mild dehydration affects sleep, but the most rigorous study I found suggests shorter sleep duration is correlated with inadequate hydration.
-
Clear nasal congestion
I believe my sleep is improved when I take active measures to make sure I’m not a mouth breather at night (in particular, I seem to dream more vividly). I will often flush my nose with this saline solution (or using a neti pot), and when I’m feeling particularly congested I’ll use these nasal strips.
-
Apple-cider vinegar
This is a weird one. I first heard of using apple-cider vinegar for sleep from Tim Ferriss. I’ll make a tea (typically Sleepy Time) and pour a tablespoon or two of apple-cider vinegar in it. I won’t lie, it tastes like you’re drinking a foot. Perhaps the foot fetishists are onto something though because this mixture causes an immediate feeling of relaxation and seems to help with sleep maintenance.
On Sleep Obsession and Anxiety
Unfortunately, going to sleep is not something we can actively control. Rather, sleep is a symptom - a consequence - of a mind at peace. This is one of the tougher pills to swallow, especially for problem solving software engineers. In a given night, not only can we not sleep by simply “trying harder” to sleep or by “solving” sleep, this can actively get in the way of sleep. Even worse, we can begin to get anxious around the notion of sleep at all. The bed becomes a place of frustration rather than relaxation.
My recommendation here if you’ve done everything right but still can’t get the z
s is to try to let go. This will be very hard at first. For better or worse, the longer you struggle with sleep the more you’ll recognize that even though you’re beyond frustrated that you’re not falling asleep, it makes things worse to dwell on that feeling.
That presentation you have tomorrow is going to go fine and it’s likely that no one will even notice any difference from your regular charismatic self. That exam you’ve been studying for so diligently will be alright too. Having experienced these situations in both undergrad, grad school, and into #adulting, I can tell you that while you may not be 100% (and we never are), your body will make sure that you’re near that when you need to be. You might take some solace knowing that those with sleep issues often rate their sleep worse than it actually is.
I try to leverage the mentality of treating yourself in this (or any) situation like you would your beloved grandmother or grandfather: gently, sympathetically, and with understanding.
On Sleeping Pills
DISCLOSURE: I AM NOT A DOCTOR, ONLY AN IDIOT WITH A KEYBOARD AND OPINIONS RIDDLED WITH PERSONAL BIAS.
I debated including my thoughts on sleeping pills here because I don’t want anyone on them to feel worse for taking them. That said, I’m strongly against the use of sleeping pills.
I was prescribed most of the major sleeping pills on the market starting at a young age. I believe they act as the worst kind of crutch: not only do they hide whatever real issue is causing an inability to sleep, some of the more common ones (like Ambien) are highly habit-forming (not to mention the awful side effects). Weaning myself off these pills was one of most difficult things I’ve had to do but it can be done. I don’t buy sleeping pills being non-habit forming either physically or psychologically; the very act of taking a sleeping pill more than once means there are situations in which we habitually take medication. Again, this prevents us from solving the real issue.
A Personal Note
To anyone who is struggling with sleep issues: please do not hesitate to reach out to me for any reason. It can be difficult to talk with people who do not have an understanding of the effects of chronic sleep deprivation. I’ve dealt with it. I know what it’s like. I know that it can make everything feel catastrophically bad.
Lastly, to anyone reading this who needs to hear it: your sleep issues, as drastic as they may be, do not have to be permanent. You, like me, can get over them with minimal (apparent) residual effects. You can live a happy and successful life. Ironically, you may one day have more gratitude for a good night’s sleep than the majority of people because you’ll know what it’s like to go without. That is a Good Thing.
Sleep well.
Further Reading
- No More Sleepless Nights by Peter Hauri
- Alex Guzey’s well-reasoned criticism of Why We Sleep by Matthew Walker