Bid-ask spread are set by the market makers who usually act as mediators between a trader and the financial market. The spread, which is taken by getting the difference between the highest price that a buyer is willing to pay for an asset and the lowest price a seller is willing to accept, serves as a transaction cost. In this way, brokers earn as traders transact by buying and selling currencies and other asset classes.
When traders buy at the ask price and sell at bid price, brokers or market makers buy at bid price and sell at ask price.
Liquidity of each asset plays a big role in the size of the bid-ask spread from one asset to another. The higher the liquidity of a market, the lower the spreads get.
To understand bid-ask spread better, consider the following example. Say the bid price for a certain stock is worth $25 while the ask price is at $27, consequently, the bid-ask spread is $2.