Why don't surjective functions form a group under composition? Let's consider the functions $f$ from $X$ to $X$ that are surjective. It's easy to see that they have a right neutral element and a right inverse. 
Why they don't form a group? What am I missing? Is injectivity needed for the associativity of composition of functions?
 A: Composition of functions is always associative. However, while surjective functions always have right inverses, these right inverses need not be surjective as well.
In fact, let $f : X\to X$ be a function. Then $f$ is surjective if and only if there exists $g : X\to X$ such that $f\circ g = id_X$. Dually, $g : X\to X$ is injective if and only if there exists $f : X\to X$ such that $f\circ g = id_X$.
So you always have a function which is a right inverse to a surjective function, but this inverse is not necessarily surjective. So the set $\operatorname{Surj}(X)$ of surjections from $X\to X$ actually does not always contain right inverses (even though these right inverses exist in the full set of functions $X\to X$). If $g$ is a right inverse of $f$, and $g\in \operatorname{Surj}(X)$, then $g$ is both injective and surjective (hence bijective). The set of bijections $X\to X$ does form a group under function composition (this is the permutation group $S_X$ of $X$). 
If $X$ is finite, then a surjection is automatically an injection as well, so you have $\operatorname{Surj}(X) = S_X$, and $\operatorname{Surj}(X)$ actually is a group.
