The second coming of Facebook

Back in 2010 Mark Zuckerberg made a very bad decision. Instead of building separate apps for iPhones, Androids, BlackBerrys, Nokia devices, and, yes, even Microsoft phones, he put his engineers to work designing a version of Facebook that could operate on any smartphone. In effect, he was betting that as different operating systems jostled for control of mobile devices, standalone apps would go away and soon we would surf websites on our phones, just as we do on PCs.

Zuckerberg was wrong. Google’s Android and Apple’s iOS quickly became the dominant mobile operating systems, and Facebook’s applications, which were built with its CEO’s web-centric worldview in mind, didn’t work well on either platform. They were buggy and slow, crashing often. A 2011 update garnered 19,000 one-star reviews in the Apple App Store within the first month. “It’s probably one of the biggest mistakes we’ve ever made,” Zuckerberg tells me during an interview at Facebook’s Menlo Park, Calif., headquarters in late March.

Just six years after it had been founded, Facebook (FB) — the company that had ushered in the social-networking era — was missing the next big shift in technology. Around the world consumers were abandoning laptops for mobile devices, busying themselves with a dizzying array of downloaded apps designed specifically for small touchscreens and people on the go. (Have you ever seen anyone play Angry Birds on a desktop?) Facebook, meanwhile, had only one engineer dedicated to the iPhone; most of its mobile team was coding for mobile web browsers.

Hidden among all the Silicon Valley success stories there are hundreds more companies that fail to catch the next wave and die. Zuckerberg was determined not to be among them. But to address his mobile problem, the wunderkind who had tasted enormous success so early in his career had to come to terms with failure, and he had to make sweeping structural and cultural changes at the young company — moves that often went against his instincts. Instead of going faster (virtually a religion at Facebook), mobile developers had to take a pause on new releases. Instead of doubling down on the mobile web, they had to embrace apps. And instead of trying to reach the broadest possible audience with a killer product, Facebook ultimately would have to pick one operating system to show off what it could really do in mobile. “I can’t overstate how much we had to retool the whole company’s development processes,” he says.

MORE: Facebook Home pre-release leaks

In early April, Zuckerberg introduced Facebook Home, a new way to provide its customers with a rich Facebook experience on mobile phones. As part of its newfound zeal for apps, the company had already successfully revamped its software for the iPhone and Android-powered devices. Facebook Home is far more ambitious; its software basically coopts certain Android devices so that Facebook’s signature elements — status updates, newsfeeds, chat — are the first things users see on the screen, even before they unlock their devices. Zuckerberg is essentially betting that really great coding will trump Facebook’s need to develop its own device or mobile platform.

The risks are huge. Facebook Home makes Zuckerberg dependent on Android, which is owned by one of Facebook’s biggest rivals, Google (GOOG). He simultaneously risks alienating Apple (AAPL), another key partner, by focusing resources on the iPhone maker’s major competitor. It also prevents him from reaping the potential benefits (mostly in quality and user experience) that could come from developing and controlling his own operating system. But if consumers and advertisers embrace the product, Zuckerberg will have a chance to prove that he knows how to reinvent the mobile experience — and in the process he will reinvent Facebook as we know it.

On a Friday after noon in October 2011, Cory Ondrejka (on-DRAY-ka) pulled his boss aside. Zuckerberg had just finished the weekly company Q&A, and he ducked into a conference room along with Facebook’s chief technology officer, Mike Schroepfer, known to everyone as Schrep. Ondrejka put it straight to Zuck: “Look, we need to throw away the [Apple] iOS app,” he remembers saying. “We need to go rebuild it.”

It was a bold recommendation, but Zuckerberg had been looking for bold when he and Schroepfer put Ondrejka in charge of mobile engineering. A gray-haired graduate of the U.S. Naval Academy (his degree is in weapons and systems engineering), Ondrejka pairs serious tech chops with experience founding companies. (Says Ondrejka: “The Facebook norm is either you just graduated from Stanford or Harvard, or you graduated from Stanford or Harvard, then went to Microsoft (MSFT), then to Google.”) He co-founded Linden Lab, home to the virtual world Second Life. He put in a brief stint in marketing at music label EMI and then started a tech company that Facebook purchased in 2010.

MORE: 17 of Apple’s favorite apps

Despite Ondrejka’s credibility, his scheme made Zuckerberg uncomfortable. Ondrejka wanted the company to lie low for a year while Facebook users complained and investors continued to decry the company’s mobile incompetence. And not just any year — this was the year that outside investors would make a very public bet on the company’s ability to succeed through an initial public offering. He was asking Zuckerberg to stop Facebook’s efforts to try to improve its lackluster app, and to turn all its resources toward readying a new one written in code for the Apple operating system. If it worked they’d start rewriting the Android app. Schroepfer and Zuckerberg peppered Ondrejka with questions. “Rewriting things usually fails,” Ondrejka remembers his boss saying. “Why would you think it would work?”

He was prepared for that question with data he had accumulated, Facebook-style. Under order to “fix mobile,” Schrep had already pulled together a group of product designers and engineers to explore “the paths that would get us to awesome” on mobile. The group considered concentrating harder on Facebook’s current strategy. Facebook’s iPhone and Android apps were hybrids: They packaged the nascent mobile-web language inside Apple- and Android-specific programming. The problem was that apps built explicitly for iOS and Android were much handsomer and cooler than Facebook’s hybrids. The group considered various other patches and jury-rigged approaches, but the path became obvious to all involved: Facebook had to rewrite the apps from scratch. What’s more, Ondrejka planned not to change anything about the apps’ design. He strongly believed that redesigning the look and feel of the apps would be a distraction from the more pressing need to improve speed and usability. In other words, Facebook users would continue to use their busted, crappy apps for nearly a year, and when the project was done, they’d have the exact same apps — only they would work. “I signed off on it,” Zuckerberg says, “but it wasn’t my instinct.”

What Zuckerberg did know was clear: Facebook’s first priority needed to be figuring out a wireless strategy. He was maniacal about it. In December 2011 he reorganized the company to embed mobile engineers in all product teams. In June 2012 he began Facebook’s annual all-hands meeting by explaining that the company’s most pressing priority was to become a mobile company. He told Facebook’s army of coders and salespeople and recruiters and designers that they could help by trading in their iPhones for Android devices.

MORE: 4 lessons for Apple in the Facebook phone

Then Zuckerberg began to walk the walk. He has no computer monitor on his desk, which is a table sandwiched between Schroepfer’s table and across from Ondrejka’s. There are no computers in his “aquarium,” the large conference room that is encased in glass on all four sides and sits in the center of campus and from which Zuckerberg does many of his product reviews. When designers and engineers file in to show off their products, his first question is nearly always, “What’s that look like on mobile?”

To get engineers to think more holistically about Facebook, Ondrejka and Schroepfer began integrating the mobile developers into product teams. At Facebook developers choose the projects they want to work on, and product groups compete to woo them. Managers sent out reports highlighting the product teams that were doing a good job. Pretty quickly teams realized that if they wanted to get praised in the weekly memo, they needed to start recruiting mobile developers.

Ondrejka and some colleagues also added discipline to the production cycle for mobile products. On the web making updates and rolling back mistakes is easy and fast, and as a result engineers were encouraged to take chances and move quickly. Mobile platforms work very differently. For one, Apple and Google, as operating system owners, vet changes to apps, which can take time. Consumers also need to remember to update their apps, and that can be an infrequent occurrence. If a developer makes a mistake, it takes a lot longer to fix. Rather than a few minutes, a Facebook user may live with that error for a few weeks.

As Facebook got smarter about developing for mobile, the demand for talented mobile engineers spiked. At first that was very hard on the organization — the company didn’t have the talent to even identify the people it needed. A couple of key acquisitions — a Dutch design firm called Sofa, and Push Pop Press, an e-book company founded by two ex-Apple iOS engineers — bolstered the mobile-development ranks. In the summer of 2012, Facebook began offering a mobile-skills training program. Engineers could sign up for a weeklong course in either iOS or Android. Many moved directly into the course after boot camp; others signed up when they were between projects. No one is an expert after a week, of course, but Schroepfer explained that the typically high-intellect trainees know “just enough to be dangerous.” The classes, which host from 12 to 23 engineers, are now held in Menlo Park, New York City, Seattle, and London. So far some 600 engineers have gone through the program. They then join product teams, where they put their new skills to work.

MORE: If Google is a rain maker, what is Apple?

The results paid off. In August 2012, Facebook released a new iPhone app that was reported to be twice as fast and garnered four- and five-star ratings in the App Store. It was a welcome piece of good news for executives, who had spent much of the summer dealing with the fallout from Facebook’s disastrous May initial public offering, in which technical glitches, allegations of selective disclosure, and hype collided, leaving individual shareholders stymied and disappointed. Facebook stock today trades at about $28, 10 bucks below its $38-a-share offering price. Zuckerberg demurs when I ask him how the IPO has changed Facebook. “We made this transition to being a public company, and at the same time we made this transition to being a mobile company,” he says, “and the transition to being a mobile company had probably 10 times the difference on the company that anything about being public had. The company has definitely changed in the last year, but I don’t think it’s because we are now public.”

For the Past few years rumors have circulated that Zuckerberg had designs on creating a Facebook phone. After all, the leading Internet juggernauts — Apple, Google, and Amazon (AMZN) — make devices. Zuckerberg considered the idea, but he couldn’t make a business case for it. Facebook had a billion users; if the company launched a device successfully, it might reach 30 million people — maybe. Says Zuckerberg: “We are not going to totally rotate our company to build something that is only going to help out 3% of our people” at best.

Still, Zuckerberg believes users want a deeper Facebook experience on their phones, and data suggest that is a safe bet. In the U.S. alone, Facebook users spend a fifth to a quarter of their phone time on the service. So Zuckerberg began to explore the potential for integrating more deeply with Apple and Android. Apple’s operating system is controlled tightly by the company. Long before Steve Jobs died, Zuckerberg had begun conversations aiming to deepen his company’s relationship with the phonemaker, and the current version of the app includes an integrated contact list, among other things. But there’s only so much that an outside developer can accomplish on the Apple platform. Zuckerberg therefore turned his attention to the Android platform, which has far deeper opportunities for customization. On Android everything is an app — even your SMS text notifications can be customized by creative software developers.

MORE: Aereo could bring down broadcast TV

Last fall Zuckerberg asked a small team of designers and engineers to figure out what else might be possible on the Android phone. “We wanted to start off trying to rethink some of those core things and say, How could these be better if, instead of the current system you have, they were people-centric in all the themes that Facebook stands for?” he says. By February the team had grown to 20 men and four women, who relocated to the “war room,” a small room with a glass garage door that opens out onto the Facebook courtyard. Zuckerberg joined the team formally for a two-hour block each Tuesday. But he also tended to show up a lot, usually right around dinner as the group was settling down for an evening of work.

The result is Facebook Home, which users could download from the Google Play Store as of April 12. To start, it will be available pre-installed on the HTC First. Users of a half-dozen Android devices can also download it. Within the next few months, as Facebook’s engineers tweak it, the app will work on many other Android phones.

Facebook Home has three components. The glossy cover feed is the first; users can scroll through the newsfeed and comment on or “like” posts from the home screen. With the second component, Chatheads, Zuckerberg has attempted to capture messaging by reorienting it around people. Whenever users receive a message either over Facebook or via text, it appears at the top of the screen next to a picture of the sender encased in a small bubble. Users can read and respond without leaving an app. The third component is the app launcher. It takes users to a familiar-looking grid of apps, including popular ones such as Pandora, Google Maps, and the Facebook app, which Home users need to open in order to publish their own updates, photos, and more.

Home is much more than just another product release. It is Facebook’s opening salvo in the battle for dominance on the mobile web. Consider for a moment its affront to Google. Using Google-made software, it has created a strategy for keeping users on Facebook.

In our conversation Zuckerberg suggests that Home is a good thing for Google. “I think that Google has this opportunity in the next year or two to start doing the things that are way better than what can be done on iPhone through the openness of their platform,” he says. He expects that the elegance of Facebook’s design will cause many of his most enthusiastic users to drop their iPhones in favor of Android devices.

MORE: This kid wants to reinvent virtual reality

But there’s a dark side for Google too. The search giant’s goal is to keep its users in the Google orbit — using Google products. But Home has inserted a layer of Facebook between an Android user and her apps, and it has made Facebook and text messaging simpler and less intrusive. Google, by contrast, requires users to unlock their phones, launch their apps, and click on the Gmail app.

Given Facebook’s engineering prowess it is possible that Home or other Home-like software could expand to the point where the technology totally consumes a device so that it isn’t even recognizable as a Google-powered phone — all thanks to Google’s open-source largesse. Think of Facebook here as potentially like a strangler fig, a type of epiphyte that gloms onto another plant or tree, growing around and over it, competing with its host for nutrients. (Google, which wasn’t involved in the development of Facebook Home, declined to comment on the product, though Zuckerberg confirms that the search giant saw it prior to launch.)

Easy Facebook access is particularly important in parts of the developing world, where the service’s next billion members are just beginning to go online. Data is prohibitively expensive in this part of the world, and Facebook has already struck deals with some carriers in which customers who buy the phones will have access to free data for a period — Facebook pays — and will be able to surf the web, or at least Facebook’s web. Sure, those customers may be buying an HTC or a Samsung phone, and it may be powered by Android, but their first experience of the web will be on Facebook, and possibly soon through Facebook Home.

If the company is successful with Home, that msay also have implications for Apple. Apple is the company that invented the design for the modern smartphone, after all — a window populated by apps. So far, no one has been able to disrupt this design interface, though many companies, including Microsoft, have tried. Most recently BlackBerry’s (BBRY) z10 introduced a new and intuitive approach to navigating the mobile web, but users have yet to embrace it. By attempting to move the design focus away from the names of the services we use on our phones and toward the images of the people to whom we connect, Facebook is introducing a new way to navigate the platform. “We’d love to be able to offer this on iPhone too,” Zuckerberg says. “We just can’t today …”

And though Facebook Home makes its debut without ads, it’s an easy leap to imagine how valuable a newsfeed ad on Facebook’s home screen may be in the future. Says Zuckerberg: “Most of the ads are just sponsored content. We don’t have any yet, but at some point we will.”

There’s always the chance that even Facebook lovers will feel besieged by too much Facebook, or that consumers have already been trained to favor apps over the deeper integration that Zuckerberg is peddling. Or it just might be that in order to be a great tech company in the 21st century, Facebook needs to overhaul itself yet again and figure out a way to make a device and develop its own operating system — or both. Luckily for Zuckerberg, he’s already been through one Facebook reboot, and he has shown he can make the tough calls.

This story is from the April 29, 2013 issue of Fortune.

Update: An earlier version of this story implied that Facebook’s deals with international phone companies are tied to the distribution of its forthcoming Home software. The relationship with carriers is not strictly related to the distribution of Home.

Subscribe to Well Adjusted, our newsletter full of simple strategies to work smarter and live better, from the Fortune Well team. Sign up today.