The subprime loans packaged as complex securities for Standard & Poor’s to rate were already failing at such a fast clip in the fall of 2006 that some analysts at the firm thought they must be seeing typographical errors.

At the time, the nation’s biggest rating agency was ­making record profits, attaching sterling ratings to mortgage-related securities that were increasingly going bad. Inside the firm’s headquarters in lower Manhattan, tensions were escalating.

“This market is a wildly spinning top, which is going to end badly,” one executive wrote in a confidential memo.

The account, culled from reams of internal e-mails, is part of civil fraud charges that the Justice Department filed late Monday against S&P in federal court in Los Angeles, accusing the firm of inflating ratings of mortgage investments and setting them up for a crash when the financial ­crisis struck.

The government is seeking $5 billion in penalties against the company to cover losses to such investors as state pension funds and federally insured banks and credit unions. The amount would be more than five times what S&P made in 2011.

Sixteen states, including Iowa, Mississippi and Illinois, joined the federal suit, and the New York attorney general said he was taking separate action. California Attorney General Kamala Harris said the state pension funds lost nearly $1 ­billion on the soured investments. The Securities and Exchange Commission has also been investigating ­possible wrongdoing at S&P.

“The action we announce today marks an important step forward in the administration’s ongoing effort to investigate — and punish — the conduct that is believed to have ­contributued to the worst ­economic crisis in recent history,” U.S. Attorney General Eric Holder said.

Standard & Poor’s defended its corporate practices Tuesday, saying the civil lawsuit filed by the Justice Department was “meritless,” and the firm would vigorously defend itself against “these unwarranted claims.”

The company said that at all times its actions reflected its best judgments about the investments at the heart of the suit — about 40 collateralized debt obligations, or CDOs, an exotic type of security made up of bundles of residential mortgage-backed securities, which in turn were composed of ­individual home loans.

The case is the first significant federal action against the ratings industry, which during the boom years bestowed high ratings that made many mortgage-related investments appear safer than they actually were.