A treaty is a bubble that will protect your castle for a specific amount of time. In that time span you cannot be spied on, raided or conquered. There are two types of treaties: First, the defeat treaty, which will be activated in case you lost a battle and a certain percentage of your maximum troops died. The second kind is the regular treaty, which can be bought in the shop or alliance market. They have different durations and you can use them whenever you like.
All treaties have one thing in common: In case you get aggressive, e.g. attack or raid a province, the treaty will end. Otherwise they will remain up for their designated duration unless canceled.