This paper analyzes a model where investors use a credit rating to decide whether To finance a firm. The rating quality depends on the credit rating agency's (CRA) effort, which is unobservable. We analyze optimal compensation contracts for the CRA that differ depending on whether the firm, investors or a social planner orders the rating. We find that rating errors are larger when the firm orders it than when investors do. However, investors ask for ratings inefficiently often. Which arrange- ment leads to a higher social surplus depends on the agents' prior beliefs about the project quality. We also show that competition among CRAs causes them to reduce their fees, put in less effort, and thus leads to less accurate ratings. Rating quality also tends to be lower for new securities. Finally, we find that optimal contracts that provide incentives for both initial ratings and their subsequent revisions can lead the CRA to be slow to acknowledge mistakes.