A perfect sleeping pill — one that gets people to fall asleep faster, and for a longer period of time, with no side effects — is still a dream.

Such a magic pill could potentially solve many problems. Millions of Americans don't get enough sleep. In a recent survey, the Centers for Disease Control and Prevention found that 35 percent of Americans are sleeping fewer than seven hours per night, the recommended healthy amount.

Good sleep doesn't just boost our feelings of well-being. There's a growing scientific consensus that it protects us against heart disease, diabetes, and obesity. In sleep labs, participants who have their sleep cycles severely thrown off for just three weeks can start to appear pre-diabetic on blood tests. (If you doubt the importance of sleep consider this: Scientists now believe that cycles of restfulness and alertness are core organizing principles of all life on Earth. Even the tiniest single-cell organisms contain the genetic coding for a circadian rhythm.)

Ever wonder how your mind works? Watch The Mind, Explained, our 5-part miniseries on the workings of the brain. Available to stream now on Netflix.

Of course, there are many prescription sleep aids on the market; unfortunately, they aren't very effective and can be addictive and dangerous.

So many prefer to walk into a corner drug store and buy an alternative for just $6 that's marketed as safe and all natural. It's melatonin, and unlike other chemicals sold as nutrition supplements in America, there's some scientific evidence to back up its claims.

But like all sleep drugs, melatonin's story is complicated. Despite the fact it's a chemical that our bodies naturally produce during sleep, how melatonin actually works, and what it's best for, is worth a good, hard look.

What is melatonin?

Melatonin was originally discovered in the 1950s, when a dermatology lab thought it played a role in skin pigmentation. The researchers all took a massive dose of their newfound chemical, expecting their skin to lighten. But they just got sleepy.

What scientists eventually realized about melatonin is this: It's the hormone that tells the body when it is nighttime. It's made in the pineal gland, a pinecone-shaped structure located deep in the brain.

"In lower vertebrates like the frog, the pineal is in fact a third eye — it’s a light-dark receptor," Dick Wurtman, a MIT cognitive scientist who help discover melatonin's function in humans, says. Scientists once assumed that it had served a function in mammals but had become a vestigial organ, bound to "disappear in a few million years," Wurtman says.

In the 1960s, Wurtman and his team at MIT found that light does still reach the pineal in mammals — through the eyes — and controls the release of melatonin. During the day, melatonin is inhibited by light. At night, it flows into the bloodstream — unless we're around bright light or blue light, which suppress the release of melatonin, and keep us up.

When it does reach the bloodstream, melatonin acts as a messenger. How the body responds to the message depends on the animal. Rats, for instance, are nocturnal, so melatonin may play a role in keeping them awake. In humans and other day-dwelling creatures, it prepares the body for rest and helps maintain that rest throughout the night.

In humans, melatonin is thought to promote sleep in two ways.

1. The exact pathway isn't well understood, but it's believed melatonin broadly suppresses the areas of the brain involved in wakefulness. Melatonin may also play a role in lowering body temperature, which is needed for sleep.

2. Melatonin helps set the overall pace of the master circadian clock in the body. Scientists have shown that when people are given melatonin in the afternoon, their body clocks can be tricked into thinking it's later, and they get sleepier sooner. This can be handy if you're suffering from jet lag, and your body thinks it's still in an earlier time zone. (More on this later.)

So how well does melatonin work?

When assessing melatonin, there are a couple of big questions researchers are asking:

Does it help people with insomnia fall asleep faster?

Does it help people stay asleep?

Does it help people sleep in new time zones?

Is it helpful for people adjusting to new shifts at work?

And does it reliably shift a person's body clock to a new phase?

The studies that have been done on these questions have tested a wide range of doses on many different populations, which makes direct comparisons among studies very difficult, and limits what we can really learn from them. But the meta analyses of melatonin that do exist does find some evidence that it can be helpful in regard to most of the above questions.

Patty Deuster, a research scientist at Uniformed Services University of the Health Sciences, was the senior author on a 2014 systematic review on melatonin. She and her team amassed a total of 35 randomized, placebo-controlled studies on healthy people with or without a diagnosis of insomnia. The effect of melatonin for insomnia was positive, but "weak," says Deutster. More studies with greater number of participants are needed.

Her review found weak positive findings for sleep onset, staying asleep, and jet lag. The evidence for shift workers and shifting the body clock were inconclusive. (However, the experts with whom I spoke said melatonin should be taken in the late afternoon to have the best chance at shifting the biological clock. Deuster's report only looked at phase-shifting studies when melatonin is given at night.)

International health organizations have analyzed melatonin research as well.

In Europe, melatonin is only available by prescription in some countries. In 2011, the European Food Safety Authority, which regulates melatonin, conducted an overview of the evidence on melatonin and concluded this: "Melatonin helps reduce the time to fall asleep.'"

That might be true, but not all researchers agree that melatonin can make a meaningful difference. Philip Gehrman, a sleep researcher and clinician at the University of Pennsylvania, says, "The research is pretty clear that melatonin is a lousy sleeping pill."

A 2005 meta review looked at this question more closely, analyzing 15 placebo-controlled studies of otherwise healthy people with insomnia. It found, on average, melatonin decreased the time it took to fall asleep compared to placebo by 3.9 minutes, it increased the time spent asleep by 13.7 minutes, and increased sleep efficiency (a ratio of time spent lying bed versus time sleeping) by 3.1 percent.

Meanwhile, a 2007 meta-analysis found that a type of prescription sleeping pill called benzodiazepines got people to sleep 10 minutes faster on average. Non-benzodiazepines (like Ambien) get people to sleep about 12.8 minutes faster. And once you're asleep, these drugs only increase the time spent asleep by 30 or so minutes. (Don't forget that these drugs can be addicting, and can kill a person in high enough doses.)

Melatonin may work best for jet lag and in people who have low melatonin

When a person is jet lagged, their body's clock is off from the clock of their destination. This can make it hard to sleep.

Melatonin may be particularly helpful for jet laggers because it can both help change a person's internal clock to match local time, and it can help them sleep after a long, restless flight.

In 2002, the Cochrane Library conducted a systematic review of melatonin's ability to help a person readjust to a new sleep schedule after jet lag at doses as small as .5 milligrams. "Melatonin is remarkably effective in preventing or reducing jet lag, and occasional short-term use appears to be safe," the review concluded, especially when used after eastward flights. "Eight of the ten trials found that melatonin, taken close to the target bedtime at the destination (10pm to midnight), decreased jet-lag from flights crossing five or more time zones."

Melatonin also seems to work much better for certain individuals.

"If your sleep problem results from a deficiency of the hormone melatonin, then melatonin will be very effective for your sleep problem," Wurtman says. If sleep problems stem from anxiety, for instance, it will be less effective.

Frank Scheer, who studies chronobiology at Harvard, agrees: An oral dose of melatonin has the best chance to make someone sleepy when internal melatonin levels are low. "In healthy subjects, if you give subjects melatonin in the middle of the day, it will help them sleep [during the middle of the day]," he says. "If I give melatonin to you during the night [when melatonin levels are higher], and you're healthy, melatonin won't have any effect on sleep."

Scheer also notes that melatonin doesn't follow a typical dose-response curve. That means taking a higher dose of melatonin doesn't necessarily result in more sleepiness.

People tend to produce less melatonin as they age, so the hormone may be more suited to treating the insomnia that's the result of aging. Melatonin also been shown to be much more effective for people with delayed sleep phase, a condition where a person's biological clock is permanently out of sync with the rest of the world.

Are there side effects?

Deuster's review looked at the reporting of adverse effects across all 35 studies, and found nothing serious. The most commonly reported side effect was drowsiness (which is kind of the point of taking melatonin) and headache.

But Scheer says there are some cases where melatonin can have adverse effects. For some people with a particular genetic variant, melatonin impairs the body's ability to process blood glucose. "It's not harmless," he says.

The risks of long-term use have also not been assessed. "There are no clear studies beyond six months of duration on melatonin's use," Scheer says.

When to take melatonin

Researchers have never done a systematic review of whether the timing of melatonin matters for people who want to get to sleep faster.

The ones I talked to also disagreed on when to take it — depending on whether they thought melatonin was better for sleep promotion or circadian clock resetting.

According to Gehrman, melatonin's ability to shift the circadian clock is stronger than its ability to promote immediate sleep. Therefore, "instead of taking it at bed time, you take it several hours before bedtime," he says. This can "advance" the biological clock around a half hour, every day.

Scheer agrees that taking melatonin in the late afternoon or early evening "will result in the largest phase advance, meaning the next day your body clock will be slightly earlier." Exposure to sunlight in the morning helps, too, he says, and may be even more effective than melatonin, or should be used in addition to melatonin, when pushing the clock forward.

Wurtman, however, doesn't recommend taking melatonin several hours before bed. He says melatonin's (albeit weak) ability to promote sleep on the spot means that people should take it shortly before bed.

Overall, Scheer says, the ideal time for any individual to take it is hard to predict. Melatonin is "not simple to use as a consumer," he says, adding that many primary care physicians may not know about its subtleties.

Another reason for caution: Melatonin isn't well regulated

Vox's Julia Belluz has done extensive reporting on the murky regulations of dietary supplements in America. Basically, she finds, the dietary supplement aisle is a minefield. Supplements don't always contain what they say they do, and they can have harmful additives. That's why it's important make sure the brand of melatonin you buy has its contents verified by a third party, like USP. (According to Wurtman, the fact that we treat melatonin as a dietary supplement is "unmitigated bullshit." None of our bodies' natural melatonin comes from diet.)

In the case of melatonin, the lax regulations means it can be sold in massive, completely, unnecessary doses. At the drug store, it's easy to pick up a 10 milligram per pill bottle of melatonin. But this is likely overkill. Many of the studies on melatonin find that it works just as well at small doses — around one milligram or less — as it does in high doses. Plus, there's a chance a huge dose will desensitize your brain to the hormone.

"If you present to your brain blood levels of melatonin that are way, way higher than any that occur normally, you desensitize the brain’s receptors to melatonin," Wurtman says. "You become less and less and less responsive."

The bottom line, according to the experts? Start with a small dose and see if it works for you.

And finally: Know that a pill may never fully combat the reasons why Americans are sleeping poorly. There are myriad ways the modern world conspires against good sleep: Stress at home and work, noisy neighborhoods, spending too little time in bright daylight, drinking too much caffeine, working odd shifts, not getting enough exercise, spending too much time with smartphones late at night, and the list goes on.