diff --git a/scripts/remove_session b/scripts/remove_session
index 7bc1078..69514df 100755
--- a/scripts/remove_session
+++ b/scripts/remove_session
@@ -11,13 +11,15 @@ use Simba::CA;
 use Bit::Vector::Judy;
 use Getopt::Long;
 
+
 $| = 1;
 
 my $ca = Simba::CA->new({
 			    dbi_file => $ENV{SIMBA_DB_CONN} || "$ENV{HOME}/.dbi/simba",
 			});
 
-my $dbh = $ca->{dbh};
+my $dbh            = $ca->{dbh};
+my $partition_size = $ca->{instances_part_size};
 
 my %opt;
 GetOptions(
@@ -39,8 +41,24 @@ if ($opt{age}) {
 }
 for my $session (@ARGV) {
     print "deleting instances of session $session\n";
+    my $old_min_id = $dbh->selectrow_array("select min(id) from instances");
     my $n_instances = $dbh->do("delete from instances where session=?", {}, $session);
     print "\t$n_instances instances deleted\n";
+
+    # Check if we just crossed into a new partition, if so, the old one is empty
+    # and should be shrunk to minimum size. 
+    #
+    # Note: This will not shrink partitions if we delete a session somewhere 
+    # in the middle, but I expect to do that rarely, and rebuilding a partition
+    # after expiring a single session isn't worthwhile anyway. If I delete lots
+    # of instances in the middle, I can always rebuild the affected partitions 
+    # manually.
+    my $new_min_id = $dbh->selectrow_array("select min(id) from instances");
+    if (int($new_min_id/$partition_size) > int($old_min_id/$partition_size)) {
+        my $partition = sprintf("p%03d", int($new_min_id/$partition_size));
+        $dbh->do("alter table instances rebuild partition $partition");
+        print "\trebuilt partition $partition\n";
+    }
     $dbh->commit();
 }
 remove_orphaned_sessions();