Quantum memory effects in atomic ensembles coupled to photonic cavities